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
本題先對數(shù)組進(jìn)行二分搜索,如果找到了目標(biāo)元素就返回相應(yīng)的index,如果最終沒有找到對應(yīng)的元素,則比較最后一個元素與目標(biāo)元素的大小。實現(xiàn)代碼如下:
本題先對數(shù)組進(jìn)行二分搜索,如果找到了目標(biāo)元素就返回相應(yīng)的index,如果最終沒有找到對應(yīng)的元素,則比較最后一個元素與目標(biāo)元素的大小。實現(xiàn)代碼如下:
1 public class Solution {
2 public int searchInsert(int[] A, int target) {
3 int length = A.length;
4 if (A.length == 0) return 0;
5 int i = 0, j = length - 1;
6 while (i < j) {
7 int mid = (i + j) / 2;
8 if (A[mid] == target) return mid;
9 if (A[mid] < target) {
10 i = mid + 1;
11 } else {
12 j = mid - 1;
13 }
14 }
15 return A[i] < target ? i + 1 : i;
16 }
17 }
2 public int searchInsert(int[] A, int target) {
3 int length = A.length;
4 if (A.length == 0) return 0;
5 int i = 0, j = length - 1;
6 while (i < j) {
7 int mid = (i + j) / 2;
8 if (A[mid] == target) return mid;
9 if (A[mid] < target) {
10 i = mid + 1;
11 } else {
12 j = mid - 1;
13 }
14 }
15 return A[i] < target ? i + 1 : i;
16 }
17 }