当前位置:网站首页>二分查找法
二分查找法
2022-07-03 09:26:00 【UniversalNature】
来自 704. 二分查找
框架如下:
// 版本二
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size(); // 定义target在左闭右开的区间里,即:[left, right)
while (left < right) {
// 因为left == right的时候,在[left, right)是无效的空间,所以使用 <
int middle = left + ((right - left) >> 1);
if (nums[middle] > target) {
right = middle; // target 在左区间,在[left, middle)中
} else if (nums[middle] < target) {
left = middle + 1; // target 在右区间,在[middle + 1, right)中
} else {
// nums[middle] == target
return middle; // 数组中找到目标值,直接返回下标
}
}
// 未找到目标值
return -1;
}
};
边栏推荐
- 20220601 Mathematics: zero after factorial
- Opencv histogram equalization
- Boston house price forecast (tensorflow2.9 practice)
- Opencv feature extraction - hog
- Judging the connectivity of undirected graphs by the method of similar Union and set search
- openCV+dlib實現給蒙娜麗莎換臉
- ECMAScript -- "ES6 syntax specification # Day1
- Leetcode - 460 LFU cache (Design - hash table + bidirectional linked hash table + balanced binary tree (TreeSet))*
- 2312. Selling wood blocks | things about the interviewer and crazy Zhang San (leetcode, with mind map + all solutions)
- I really want to be a girl. The first step of programming is to wear women's clothes
猜你喜欢

High imitation wechat

Leetcode - 5 longest palindrome substring

A complete answer sheet recognition system

3.1 Monte Carlo Methods & case study: Blackjack of on-Policy Evaluation

A super cool background permission management system

LeetCode - 900. RLE iterator

Leetcode-106: construct a binary tree according to the sequence of middle and later traversal

Policy Gradient Methods of Deep Reinforcement Learning (Part Two)

【SQL】一篇带你掌握SQL数据库的查询与修改相关操作

Opencv image rotation
随机推荐
What can I do to exit the current operation and confirm it twice?
Yolov5 creates and trains its own data set to realize mask wearing detection
重写波士顿房价预测任务(使用飞桨paddlepaddle)
一步教你溯源【钓鱼邮件】的IP地址
LeetCode - 900. RLE iterator
Mise en œuvre d'OpenCV + dlib pour changer le visage de Mona Lisa
【毕业季】图匮于丰,防俭于逸;治不忘乱,安不忘危。
【C 题集】of Ⅵ
Pycharm cannot import custom package
LeetCode - 1172 餐盘栈 (设计 - List + 小顶堆 + 栈))
Julia1.0
2018 y7000 upgrade hard disk + migrate and upgrade black apple
Data preprocessing - Data Mining 1
Leetcode bit operation
. DLL and Differences between lib files
20220601 Mathematics: zero after factorial
CV learning notes - feature extraction
侯捷——STL源码剖析 笔记
LeetCode - 919. Full binary tree inserter (array)
Matplotlib drawing