当前位置:网站首页>二分查找法
二分查找法
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;
}
};
边栏推荐
- Leetcode - 706 design hash mapping (Design)*
- Policy Gradient Methods of Deep Reinforcement Learning (Part Two)
- Leetcode - 1670 conception de la file d'attente avant, moyenne et arrière (conception - deux files d'attente à double extrémité)
- 2018 y7000 upgrade hard disk + migrate and upgrade black apple
- Leetcode - 1670 design front, middle and rear queues (Design - two double ended queues)
- . DLL and Differences between lib files
- 2.1 Dynamic programming and case study: Jack‘s car rental
- GAOFAN Weibo app
- Stroke prediction: Bayesian
- Boston house price forecast (tensorflow2.9 practice)
猜你喜欢
3.3 Monte Carlo Methods: case study: Blackjack of Policy Improvement of on- & off-policy Evaluation
2018 y7000 upgrade hard disk + migrate and upgrade black apple
Cases of OpenCV image enhancement
The underlying principle of vector
CV learning notes convolutional neural network
LeetCode - 1670 設計前中後隊列(設計 - 兩個雙端隊列)
LeetCode - 1172 餐盘栈 (设计 - List + 小顶堆 + 栈))
LeetCode - 715. Range module (TreeSet)*****
Are there any other high imitation projects
Basic use and actual combat sharing of crash tool
随机推荐
Handwritten digit recognition: CNN alexnet
ECMAScript -- "ES6 syntax specification # Day1
Rewrite Boston house price forecast task (using paddlepaddlepaddle)
CV learning notes - reasoning and training
Powshell's set location: unable to find a solution to the problem of accepting actual parameters
An open source OA office automation system
Data preprocessing - Data Mining 1
Opencv interview guide
重写波士顿房价预测任务(使用飞桨paddlepaddle)
A complete answer sheet recognition system
20220605 Mathematics: divide two numbers
20220608 other: evaluation of inverse Polish expression
Hands on deep learning pytorch version exercise solution - 3.1 linear regression
Leetcode - 705 design hash set (Design)
Neural Network Fundamentals (1)
Leetcode - 1670 design front, middle and rear queues (Design - two double ended queues)
20220609其他:多数元素
openCV+dlib實現給蒙娜麗莎換臉
Leetcode-404: sum of left leaves
Leetcode - 5 longest palindrome substring