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
Solution1:标准BinarySearch写法即可
思路: 当找不到时候返回的是增序序列该插入的位置,因为mid is biased to the left when mid = (i + j) / 2 比如[0, 1, 2, 3] mid = 1 但其实应该是1.5。所以当想找增序序列该在后追加的位置时 mid = (i + j + 1) / 2,当然也可以用mid = (i + j) / 2 得到插入位置再减1,这里就是说明作用。降序序列时要反过来。
Solution2:直接调用Arrays.binarySearch(数组, start, end, target);
Time Complexity: O(1) Space Complexity: O(N)
Solution3:BinarySearch Template写法
思路:
Solution1 Code:
class Solution1 {
public int searchInsert(int[] A, int target) {
int low = 0, high = A.length - 1;
while(low <= high) {
int mid = (low + high) / 2;
if(A[mid] == target) return mid;
else if(A[mid] > target) high = mid - 1;
else low = mid + 1;
}
return low;
}
}
Solution2 Code:
class Solution {
public int searchInsert(int[] A, int target) {
int index = Arrays.binarySearch(A, 0, A.length, target);
if(index < 0) index = -1 * index - 1;
return index;
}
}
Solution3 BinarySearch Template Code:
class Solution {
public int searchInsert(int[] nums, int target) {
if(nums == null || nums.length == 0) return 0;
int left = 0, right = nums.length - 1;
while(left + 1 < right) {
int mid = left + (right - left) / 2;
if(nums[mid] == target) {
return mid;
}
else if(nums[mid] < target) {
left = mid;
}
else {
right = mid;
}
}
if(nums[left] >= target) {
return left;
}
else if(nums[right] >= target) {
return right;
}
else {
return right + 1;
}
}
}