给定一个排序的整数数组 nums 和一个整数目标值 target ,请在数组中找到 target ,并返回其下标。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
思路:
常规的二分查找,题意是找最左边的下标,那就r=mid
代码:
class Solution {
public:int searchInsert(vector<int>& nums, int target) {int l=0;int r=nums.size();while(l<r){int mid=(l+r)/2;if(nums[mid]>=target)r=mid;else l=l+1;}return l;}
};
点击此处跳转我的leetcode题解链接
运行结果: