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 → 0Basic binary search.
public int searchInsert(int[] A, int target) { int n = A.length; int l = 0, r = n - 1; while(l <= r) { int mid = l + (r - l) / 2; if(A[mid] == target) { return mid; } else if(A[mid] > target) { r = mid - 1; } else l = mid + 1; } return l; }
没有评论:
发表评论