Leetcode#35 Search Insert Position

原题地址

二分搜索变种,注意到当左指针和右指针相交后,应该插入的位置总是在左指针处,所以直接返回左指针即可。

代码:

 1 int searchInsert(int A[], int n, int target) {
 2         int l = 0;
 3         int r = n - 1;
 4         
 5         while (l <= r) {
 6             int m = (l + r) / 2;
 7             if (A[m] == target)
 8                 return m;
 9             else if (A[m] < target)
10                 l = m + 1;
11             else
12                 r = m - 1;
13         }
14         
15         return l;
16 }
原文地址:https://www.cnblogs.com/boring09/p/4255478.html