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
Common method, time complexity is O (n)
1 classSolution {2 Public:3 intSearchinsert (intA[],intNinttarget) {4 if(n==0)returnNULL;5 intI=0;6 for(i=0; i<n;i++)7 {8 if(target<=A[i])9 returni;Ten } One returni; A } -};
Dichotomy, time complexity of O (LOGN)
1 classSolution {2 Public:3 intSearchinsert (intA[],intNinttarget) {4 intstart=0;5 intend=n-1;6 intindex= (start+end)/2;7 while(start<end)8 {9 if(a[index]>target)Ten { Oneend=index-1; Aindex= (start+end)/2; -}Else if(a[index]<target) { -start=index+1; theindex= (start+end)/2; -}Else{ - returnindex; - } + } - if(a[start]<target) { + returnstart+1; A}Else{ at returnstart; - } - } -};
"Leetcode" Search Insert Position