leetcode -- 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 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

思路:

二分搜索,如search到则返回,否则将target与二分搜索循环终止处的数进行比较:

二分搜索循环终止时:l==r

当A[l] >= target时,将target插入到l之前,如line 20,之前考虑相等时将该数放在l之后,但有个test case没跑过去([1], 1 expected: 0)

否则放在l之后

 1 public int searchInsert(int[] A, int target) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         int len = A.length;
 5         int l = 0;
 6         int r = len - 1;
 7         while(l < r){
 8             int m = (l + r) / 2;
 9             if(A[m] == target){
10                 return m;
11             }
12             
13             if(A[m] < target){
14                 l = m + 1;
15             } else {
16                 r = m - 1;
17             }
18         }
19         
20         if(A[l] >= target){
21             return l;
22         } else {
23             return l + 1;
24         }
25     }

 

你可能感兴趣的:(LeetCode)