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
最初的想法是从头到尾遍历这个数组,这样也是可以做的
class Solution { public: int searchInsert(int A[], int n, int target) { if(target<=A[0]) return 0; if(target==A[n-1]) return n-1; if(target>A[n-1]) return n; int begin=0,last=n-1; while(A[begin]<target) { begin++; } return begin; } };不过用二分法在某些情况的确可以提高查找效率
class Solution { public: int searchInsert(int A[], int n, int target) { if(target<=A[0]) return 0; if(target==A[n-1]) return n-1; if(target>A[n-1]) return n; int mid,i=0,j=n-1; while(i<=j) { mid=int((i+j)/2); if(A[mid]==target){ return mid; } else if(A[mid]>target) { j=mid-1; } else { i=mid+1; } } return i; } };