Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6]
, 5 → 2
[1,3,5,6]
, 2 → 1
[1,3,5,6]
, 7 → 4
[1,3,5,6]
, 0 → 0
看着复杂,其实就是二分查找,平时不存在一般返回-1,这道题就返回low的值就好了
class Solution {
public:
int searchInsert(int A[], int n, int target) {
int mid, low=0, high=n;
while (low<high) {
mid = low+((high-low)>>1);
if (A[mid] >= target)
high = mid;
else
low = mid+1;
}
if ((high<n) && A[high]==target)
return high;
return low;
}
};