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.
Example 1:
Input: [1,3,5,6], 5output:2
Example 2:
Input: [1,3,5,6], 2output:1
Example 3:
Input: [1,3,5,6], 7output:4
Example 4:
Input: [1,3,5,6], 0output:0
Test instructions: Give a sorted array and a number to be searched. Ask for the location where the number is located, and if it does not exist, return where it should exist
Binary search (ashamed to say, I look at the two points often error, so when the array is less than 5 I used to scan, not very affect performance)
classSolution { Public intSearchinsert (int[] Nums,inttarget) { inti = 0; intj = Nums.length-1; intindex =-1; while(J-i > 5) { intMid = (i + j)/2; if(Nums[mid] >target) {J=mid; } Else if(Nums[mid] <target) {i=mid; } Else{Index=mid; Break; } } for(intK = i; K <= J; k++) { if(Nums[k] = =target) {Index=K; Break; } if(K < J && Nums[k] < target && nums[k + 1] >target) {Index= k + 1; Break; } } if(Nums[0] >target) Index= 0; if(Nums[nums.length-1] <target) Index=nums.length; returnindex; }}
[Leetcode] 35. Search Insert Position