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
"Problem Analysis"
Given a sorted array, there are no duplicate numbers in the array. Given a number to find the position where the number appears, if the number does not exist in the array, it returns where the number should be inserted if it is inserted.
Ideas
When it comes to sorted arrays, we generally use a binary lookup algorithm. If the target number is present, the result is returned directly. What if it doesn't exist?
Look at the binary search, left and right are equal, if the value and the target value at the same time, left is the result should be returned, otherwise we compare the target value and subscript left corresponding to the value of the size. Returns LEFT+1 if the target value is large, otherwise returns left.
"Java Code"
1 Public classSolution {2 Public intSearchinsert (int[] Nums,inttarget) {3 if(Nums.length = = 0 | | nums = =NULL)return0;4 5 intleft = 0;6 intright = Nums.length-1;7 8 while(Left <=Right ) {9 if(left = =Right ) {Ten if(Nums[left] = = target)returnLeft ; One Else Break; A } - intMid = (Right-left)/2 +Left ; - if(Nums[mid] > target) right = Mid-1; the Else if(Nums[mid] < target) left = mid + 1; - Else returnmid; - } - if(Nums[left] < target)returnLeft+1; + Else returnLeft ; - } +}
Leetcode OJ 35. Search Insert Position