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 int searchInsert(int A[], int n, int target) { 2 return binarySearch(A,0,n-1,target); 3 } 4 int binarySearch(int A[],int s,int e,int target){ 5 while(s<=e){ 6 int mid=s+(e-s)/2; 7 if(A[mid]==target) return mid; 8 if(s==e) return A[mid]>target?s:s+1; 9 if(target<A[mid]) { 10 if(mid==s) return s; 11 e=mid-1; 12 } 13 else { 14 if(mid==e) return e+1; 15 s=mid+1; 16 } 17 } 18 }