Question
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
Solution 1--Naive
Iterate the array and compare target with ith and (i+1) th element. Time complexity O (n).
1 Public classSolution {2 Public intSearchinsert (int[] Nums,inttarget) {3 if(nums==NULL)return0;4 if(Target <= nums[0])return0;5 for(inti=0; i<nums.length-1; i++){6 if(Target > Nums[i] && target <= nums[i+1]){7 returnI+1;8 }9 }Ten returnnums.length; One } A}Solution 2--Binary Search
If the target number doesn ' t exist in original array and then after iteration, it must is pointed by low pointer.
Time Complexity O (log (n))
1 Public classSolution {2 Public intSearchinsert (int[] Nums,inttarget) {3 if(Nums = =NULL|| Nums.length = = 0)4 return0;5 intStart = 0, end = nums.length-1, Mid = (End-start)/2 +start;6 while(Start <=end) {7Mid = (End-start)/2 +start;8 if(Nums[mid] = =target)9 returnmid;Ten Else if(Nums[mid] <target) OneStart = mid + 1; A Else -End = Mid-1; - } the returnstart; - } -}
Search Insert Position Solution