题目:35. 搜索插入位置 - 力扣(LeetCode)
思想:常规的二分,很简单的理解是当大于所有数时要在right的边界+1插入
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left = 0;
int right =nums.size()-1;
while(left<=right)
{
int mid = ( left + right )/2;
if(nums[mid] > target)
right = mid - 1 ;
else if(nums[mid] < target)
left = mid + 1;
else return mid;
}
return right+1;
}
};
有趣的是可以看看此时的时间
但如果变成left
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left = 0;
int right =nums.size()-1;
while(left<=right)
{
int mid = ( left + right )/2;
if(nums[mid] > target)
right = mid - 1 ;
else if(nums[mid] < target)
left = mid + 1;
else return mid;
}
return left;
}
};
时间明显减少了hh,此时left已经根据代码自动变成了mid+1,减少了计算量