Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would is if it were inserted in order.
Assume no duplicates in the array.
Here is 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
Idea: The sequential sequence of the sequence is searched by the dichotomy method
classSolution { Public: intSearchinsert (intA[],intNinttarget) { if(n==0)return 0; BinarySearch (A,0, N-1, Target); returnresult; } voidBinarySearch (intA[],intStartintEndintTarget) {//find the first value >= target if(start==end) { if(A[start] < target) result = start+1; Elseresult =start; return; } intMID = start + ((End-start) >>1);//Prevent overflow if(A[mid] < target) BinarySearch (a,mid+1, end, target); Else if(A[mid] >target) BinarySearch (A,start, Mid, Target); Elseresult =mid;}Private: intresult;};
. Search Insert Position (Array)