0
点赞
收藏
分享

微信扫一扫

搜索插入位置:Search Insert Position

上善若水山西太原 2022-12-01 阅读 80


​​https://leetcode.com/problems/search-insert-position/​​

注意以上实现方式有一个好处,就是当循环结束时,如果没有找到目标元素,那么left一定停在恰好比目标大的index上,right一定停在恰好比目标小的index上,所以个人比较推荐这种实现方式。

class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int len=nums.size();
if(len==0)
return 0;
int left=0,right=len-1;
while(left<=right){
int mid=left+(right-left)/2;
if(target==nums[mid])
return mid;
else if(target<nums[mid])
right=mid-1;
else
left=mid+1;
}
return left;
}
};


举报

相关推荐

0 条评论