当前位置:网站首页>leetcode704. 二分查找(查找某个元素,简单,不同写法)
leetcode704. 二分查找(查找某个元素,简单,不同写法)
2022-07-06 06:55:00 【重you小垃】


要点:始终维护的区间和初始时的位置是一样的即可。
1:左开右开
class Solution {
public:
int search(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) return mid;
else if (nums[mid] > target) r = mid;
else l = mid;
}
return -1;
}
};
2:左闭右闭
class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (nums[mid] == target) return mid;
else if (nums[mid] > target) r = mid - 1;
else l = mid + 1;
}
return -1;
}
};
3:左开右闭
class Solution {
public:
int search(vector<int>& nums, int target) {
int l = -1, r = nums.size() - 1;
while (l < r) {
int mid = l + (r - l) / 2 + 1;//mid偏向r一边,否则会陷入死循环
if (nums[mid] == target) return mid;
else if (nums[mid] > target) r = mid - 1;
else l = mid;
}
return -1;
}
};
4:左闭右开
class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0, r = nums.size();
while (l < r) {
int mid = l + (r - l) / 2;
if (nums[mid] == target) return mid;
else if (nums[mid] > target) r = mid;
else l = mid + 1;
}
return -1;
}
};
边栏推荐
- [Yu Yue education] flower cultivation reference materials of Weifang Vocational College
- Day 245/300 JS forEach 多层嵌套后数据无法更新到对象中
- 成功解决AttributeError: Can only use .cat accessor with a ‘category‘ dtype
- Short video, more and more boring?
- 中青看点阅读新闻
- 机器学习植物叶片识别
- 【每日一题】729. 我的日程安排表 I
- Blue Bridge Cup zero Foundation National Championship - day 20
- Introduction to ros2 installation and basic knowledge
- 编译,连接 -- 笔记 -2
猜你喜欢

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

hydra常用命令

Practical guidance for interface automation testing (Part I): what preparations should be made for interface automation

Fedora/rehl installation semanage

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

My creation anniversary

Classification des verbes reconstruits grammaticalement - - English Rabbit Learning notes (2)

UWA Pipeline 2.2.1 版本更新说明

云上有AI,让地球科学研究更省力

Huawei equipment configuration ospf-bgp linkage
随机推荐
LeetCode Algorithm 2181. 合并零之间的节点
Arduino tutorial - Simon games
WPF之MVVM
Due to high network costs, arbitrum Odyssey activities are suspended, and nitro release is imminent
Suspended else
P5706 [deep foundation 2. Example 8] redistributing fat house water -- February 13, 2022
UniPro甘特图“初体验”:关注细节背后的多场景探索
RichView TRVStyle 模板样式的设置与使用
开源的网易云音乐API项目都是怎么实现的?
Fast target recognition based on pytorch and fast RCNN
SQL Server Manager studio (SSMS) installation tutorial
L'Ia dans les nuages rend la recherche géoscientifique plus facile
Prefix and array series
ROS学习_基础
Supporting title of the book from 0 to 1: ctfer's growth road (Zhou Geng)
机器学习植物叶片识别
19. Actual memory management of segment page combination
将ue4程序嵌入qt界面显示
LeetCode每日一题(1870. Minimum Speed to Arrive on Time)
Depth residual network