当前位置:网站首页>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也对
}
};
注意的地方:
边栏推荐
猜你喜欢

医疗软件检测机构怎么找,一航软件测评是专家

After sharing the clone remote project, NPM install reports an error - CB () never called! This is an error with npm itself.

hydra常用命令

Explain in detail the functions and underlying implementation logic of the groups sets statement in SQL

Suspended else

万丈高楼平地起,每个API皆根基

这个高颜值的开源第三方网易云音乐播放器你值得拥有

Is it difficult for girls to learn software testing? The threshold for entry is low, and learning is relatively simple
![[ 英語 ] 語法重塑 之 動詞分類 —— 英語兔學習筆記(2)](/img/3c/c25e7cbef9be1860842e8981f72352.png)
[ 英語 ] 語法重塑 之 動詞分類 —— 英語兔學習筆記(2)

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
云上有AI,让地球科学研究更省力
AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models.common‘ from ‘/home/yolov5/models/comm
顶测分享:想转行,这些问题一定要考虑清楚!
Suspended else
Three methods of adding color to latex text
Machine learning plant leaf recognition
C language_ Double create, pre insert, post insert, traverse, delete
UWA Pipeline 2.2.1 版本更新说明
Practical guidance for interface automation testing (Part I): what preparations should be made for interface automation
UNIPRO Gantt chart "first experience": multi scene exploration behind attention to details
同事上了个厕所,我帮产品妹子轻松完成BI数据产品顺便得到奶茶奖励
Leetcode daily question (971. flip binary tree to match preorder traversal)
Briefly describe the differences between indexes, primary keys, unique indexes, and joint indexes in mysql, and how they affect the performance of the database (in terms of reading and writing)
将ue4程序嵌入qt界面显示
Classification des verbes reconstruits grammaticalement - - English Rabbit Learning notes (2)
P5706 [deep foundation 2. Example 8] redistributing fat house water -- February 13, 2022
因高额网络费用,Arbitrum 奥德赛活动暂停,Nitro 发行迫在眉睫
简单描述 MySQL 中,索引,主键,唯一索引,联合索引 的区别,对数据库的性能有什么影响(从读写两方面)
Database basics exercise part 2