问题原始链接 https://leetcode.com/problems/search-insert-position
给定一个有序数组和一个目标值,如果在数组中找到该值则返回它的索引,否则返回该值将插入到数组中的索引。
你可以假设数组中没有重复值。
以下是一些例子。
[1,3,5,6],5->2
[1,3,5,6],2->1
[1,3,5,6],7->4
[1,3,5,6],0->0
使用二分查找。
public class Solution {
public static int searchInsert(int[] nums, int target) {
if (nums == null) {
return -1;
}
if (nums.length == 0) {
return 0;
}
return searchInsert(nums, target, 0, nums.length - 1);
}
private static int searchInsert(int[] nums, int target, int low, int high) {
if (low == high) {
if (nums[low] == target) {
return getInsertEquals(nums, low);
}
return nums[low] < target ? low + 1 : low;
}
if (target <= nums[low]) {
return low;
}
if (target > nums[high]) {
return high + 1;
}
int mid = (low + high) >> 1;
if (nums[mid] == target) {
return getInsertEquals(nums, mid);
} else if (nums[mid] > target) {
return searchInsert(nums, target, low, mid - 1 < low ? low : mid - 1);
} else {
return searchInsert(nums, target, mid + 1, high);
}
}
private static int getInsertEquals(int[] nums, int i) {
while (i - 1 >= 0 && nums[i - 1] == nums[i]) {
i--;
}
return i;
}
}