35. 搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-insert-position
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
想法
- 如果直接使用二分,那么退出的位置l,实际上就是应该插入的位置。
- 如果二分不用等号,那么意味着最后统一处理。
class Solution {
public int searchInsert(int[] nums, int target) {
int l=0,r=nums.length-1;
while(l<=r){
int mid=(l+r)/2;
if(nums[mid]==target) return mid;
else if(nums[mid]>target) r=mid-1;
else l=mid+1;
}
return l;
}
}
class Solution {
public int searchInsert(int[] nums, int target) {
int l=0,r=nums.length-1;
while(l<r){
int mid=(l+r)/2;
if(nums[mid]==target) return mid;
else if(nums[mid]>target) r=mid-1;
else l=mid+1;
}
if(nums[l]>=target) return l;
else return l+1;
}
}