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
从头到尾扫描一遍的复杂度是O(n),有比这个更快的方法。肯定也是想到二分查找。如果目标值存在,那么情况就和二分查找一样,返回当前下标。
难点就在于如果目标值不在数组里,怎么找到插入下标
解题思路:
通过二分查找找出目标值,如果能找到,则返回当前下标;如果不能,要想想是返回查找区间开始start,结束end,还是中间值mid?循环调用二分查找时start总是小于等于end,循环结束后,start大于end,start记录了第一个大于目标值的元素的下标,所以返回start
public class Solution {
public int searchInsert(int[] nums, int target) {
int start = 0;
int end = nums.length-1;
int mid;
while (start <= end) {
mid = (start + end) / 2;
if (nums[mid] == target) {
return mid;
}else if (nums[mid] < target) {
//往目标值靠近
start = mid + 1;
}else {
end = mid-1;
}
}
return start;
}
}

本文介绍了一种利用二分查找算法解决特定问题的方法,即在一个已排序的数组中寻找目标值的位置,若不存在则返回合适的插入位置。文章详细阐述了解决方案的实现思路,并提供了完整的代码示例。
468

被折叠的 条评论
为什么被折叠?



