Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are 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
参考 : http://www.cnblogs.com/feiling/p/3232368.html
二分搜索,如search到则返回,否则将target与二分搜索循环终止处的数进行比较:
二分搜索循环终止时:l==r
当A[l] >= target时,将target插入到l之前,如line 20,之前考虑相等时将该数放在l之后,但有个test case没跑过去([1], 1 expected: 0)
否则放在l之后
1 public class Solution { 2 public int searchInsert(int[] A, int target) { 3 int len = A.length; 4 int l = 0; 5 int r = len-1; 6 while(l < r){ 7 int m = (l+r)/2; 8 if(A[m] == target){ 9 return m; 10 }else if(A[m] < target){ 11 l = m +1; 12 }else{ 13 r = m-1; 14 } 15 } 16 17 if(A[l] >= target){ 18 return l; 19 }else{ 20 return l+1; 21 } 22 } 23 }