当前位置:网站首页>leetcode35. 搜索插入位置(简单,找插入位置,不同写法)
leetcode35. 搜索插入位置(简单,找插入位置,不同写法)
2022-07-06 06:55:00 【重you小垃】
二分:库函数
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
return lower_bound(nums.begin(), nums.end(), target) - nums.begin();
}
};
跟 leetcode leetcode704. 二分查找(查找某个元素,简单,不同写法)
区间不同,这里的[l, r] 是 [0, n] 而不是[0, n - 1]
https://blog.csdn.net/zhangjiaji111/article/details/125601772
右边界n是越界数组的,如果用右开,会访问到nums[n],因此右边只能用右闭:左闭右闭 或者 左开右闭
1:左开右闭
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int l = -1, r = nums.size();
while (l + 1 < r) {
int mid = l + (r - l) / 2;
if (nums[mid] >= target) r = mid;
else l = mid;
}
return r;
}
};
2:左闭右闭
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size();
int l = 0, r = n;
while (l < r) {
//当l==r时应该退出循环,所以没有==
int mid = l + (r - l) / 2;
if (nums[mid] >= target) r = mid;
else l = mid + 1;
}
return l; //return r也对
}
};
注意的地方:
边栏推荐
- Bitcoinwin (BCW): the lending platform Celsius conceals losses of 35000 eth or insolvency
- 这个高颜值的开源第三方网易云音乐播放器你值得拥有
- Do you really know the use of idea?
- 一文读懂简单查询代价估算
- Delete external table source data
- SAP SD发货流程中托盘的管理
- hydra常用命令
- Supporting title of the book from 0 to 1: ctfer's growth road (Zhou Geng)
- 从autojs到冰狐智能辅助的心里历程
- When my colleague went to the bathroom, I helped my product sister easily complete the BI data product and got a milk tea reward
猜你喜欢
(practice C language every day) reverse linked list II
My creation anniversary
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
Introduction and underlying analysis of regular expressions
Pallet management in SAP SD delivery process
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
接口自动化测试框架:Pytest+Allure+Excel
SAP SD发货流程中托盘的管理
[unity] how to export FBX in untiy
Proteus -- Serial Communication parity flag mode
随机推荐
librosa音频处理教程
Windows Server 2016 standard installing Oracle
Day 239/300 注册密码长度为8~14个字母数字以及标点符号至少包含2种校验
How to find a medical software testing institution? First flight software evaluation is an expert
Depth residual network
【Hot100】739. 每日溫度
Day 246/300 SSH connection prompt "remote host identification has changed!"
Redis Foundation
P5706 [deep foundation 2. Example 8] redistributing fat house water -- February 13, 2022
The difference between get and post request types
[hot100] 739. Température quotidienne
Day 246/300 ssh连接提示“REMOTE HOST IDENTIFICATION HAS CHANGED! ”
接口自动化测试实践指导(上):接口自动化需要做哪些准备工作
[unity] how to export FBX in untiy
前缀和数组系列
【每日一题】729. 我的日程安排表 I
When my colleague went to the bathroom, I helped my product sister easily complete the BI data product and got a milk tea reward
中青看点阅读新闻
19.段页结合的实际内存管理
Call, apply, bind rewrite, easy to understand with comments