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

SOLUTION 1:

用九章算法的模板查找结束后判断一下即可。:

 1 public int searchInsert1(int[] A, int target) {
 2         if (A == null || A.length == 0) {
 3             return 0;
 4         }
 5         
 6         int left = 0;
 7         int right = A.length - 1;
 8         
 9         while (left < right - 1) {
10             int mid = left + (right - left) / 2;
11             int num = A[mid];
12             
13             if (num == target) {
14                 return mid;
15             } else if (num < target) {
16                 left = mid + 1;
17             } else {
18                 right = mid - 1;
19             }
20         }
21         
22         // bug 1: should use <=
23         if (target <= A[left]) {
24             return left;
25         // bug 2: should use <= . consider that may the result exit in left or right.    
26         } else if (target <= A[right]) {
27             return right;
28         }
29         
30         return right + 1;
31     }
View Code

相关文章: