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.
(翻译:给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。)
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
这道题其实是二分法的变形,我在这里写了四种不同的二分法来实现题目要求,其中前两种是同一个思路,后两种是同一个思路:
写法一:
public int searchInsert(int[] nums, int target) {
int start = 0;
int end = nums.length;
while (start < end) {
int mid = (start + end) >> 1;
int midNum = nums[mid];
if (midNum < target) {
start = mid + 1;
} else {
end = mid;
}
}
return start;
}
写法二:
public int searchInsert1(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
int ans = nums.length;
while (start <= end) {
int mid = (start + end) >> 1;
int midNum = nums[mid];
if (midNum >= target) {
ans = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
return ans;
}
写法三:
public int searchInsert2(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
while (start + 1 < end) {
int mid = (end - start) / 2 + start;
if (target < nums[mid]) end = mid;
else if (target > nums[mid]) start = mid;
else return mid;
}
if (target <= nums[start]) {
return start;
} else if (target <= nums[end]) {
return end;
} else {
return end + 1;
}
}
写法四:
public int searchInsert3(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
//int mid = (left + right)/2;
int mid = (right - left) / 2 + left;
if (nums[mid]==target) return mid;
else if(nums[mid] > target) right = mid - 1;
else left = mid + 1;
}
return left;
}