Search Insert Position
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:
Use the nine-chapter algorithm to find the template after the end of the judgment. :
1 Public intSearchInsert1 (int[] A,inttarget) {2 if(A = =NULL|| A.length = = 0) {3 return0;4 }5 6 intleft = 0;7 intright = A.length-1;8 9 while(Left < Right-1) {Ten intMid = left + (right-left)/2; One intnum =A[mid]; A - if(num = =target) { - returnmid; the}Else if(Num <target) { -left = mid + 1; -}Else { -right = Mid-1; + } - } + A //bug 1:should use <= at if(Target <=A[left]) { - returnLeft ; - //bug 2:should use <=. Consider, the result exit in left or right. -}Else if(Target <=A[right]) { - returnRight ; - } in - returnRight + 1; to}View CodeSolution 2:
can also be very concise:
Http://fisherlei.blogspot.com/2013/01/leetcode-search-insert-position.html
http://blog.csdn.net/fightforyourdream/article/details/14216321
The reason that this can be word is:
1. When target exists, of course it returns to mid.
2. When target is greater than all numbers. Then L, R will run to the far right, and L will continue to run out a lattice, that is, l will point to Len, that is, the value to find.
3. When target is less than the number of all. L,r runs to the far left, and R continues to move one cell to the left, and L points to the target position.
4. When target is less than a certain number a, and is greater than a certain number B. Then L, R aborts, R will point to the target position in the b,l at a,l.
If the target is not found, the value of L at the end of the loop is closest to target but the number of > target is in the array position.
1 //Sol 2:2 Public intSearchinsert (int[] A,inttarget) {3 if(A = =NULL|| A.length = = 0) {4 return0;5 }6 7 intleft = 0;8 intright = A.length-1;9 Ten while(Left <=Right ) { One intMid = left + (right-left)/2; A intnum =A[mid]; - - if(num = =target) { the returnmid; -}Else if(Num <target) { -left = mid + 1; -}Else { +right = Mid-1; - } + } A at returnLeft ; -}View CodeGtihub:
Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/divide2/SearchInsert.java
Leetcode:search Insert Position Problem Solving report