Description: 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 1: An intuitive idea, traversing an array, once the current element is >=target, the position of the current element is the insertion position, and the boundary problem is dealt with. Time complexity: O (N)
1 classSolution {2 Public:3 intSearchinsert (intA[],intNinttarget) {4 5 if(Target > a[n-1])6 returnN;7 8 Else { 9 for(inti =0; I < n; i++) {Ten if(A[i] >=target) One returni; A } - } - } the};
Idea 2: Because the given array is already ordered, you can use binary search to compare the size of A[mid] with target. Complexity of Time: O (LOGN)
1 classSolution {2 Public:3 intSearchinsert (intA[],intNinttarget) {4 5 intStart =0;6 intEnd = N-1;7 intMID =0;8 9 while(End >=start) {Ten OneMid = (start + end)/2; A if(target = =A[mid]) - returnmid; - Else if(Target >A[mid]) theStart = mid +1; - Else -End = Mid-1; - } + - if(Target >A[mid]) + returnMid +1; A Else at returnmid; - - } -};
Leetcode problem 35:search Insert Position