题目链接:
题目描述:
解法
找二段性
C++ 算法代码:
class Solution
{
public:
int searchInsert(vector<int>& nums, int target)
{
int left = 0, right = nums.size() - 1;
while(left < right)
{
int mid = left + (right - left) / 2;
if(nums[mid] < target) left = mid + 1;
else right = mid;
}
if(nums[left] < target) return right + 1;
return right;
}
};
图解
例如:nums = [1,3,5,6], target = 5
经过while(left < right)
循环,找到左端点,也就是left=right
的时候。得到左端点下标为2
返回2