2022-11-21 12:04:27 +00:00
|
|
|
|
# 二分查找
|
|
|
|
|
|
2022-11-24 08:44:36 +00:00
|
|
|
|
适用于数组有序的情况下查找目标值。
|
|
|
|
|
|
|
|
|
|
## 写法一
|
|
|
|
|
|
|
|
|
|
针对左闭右闭区间(即 `[left, right]`):
|
2022-11-21 12:04:27 +00:00
|
|
|
|
|
|
|
|
|
```cpp
|
2022-11-24 08:44:36 +00:00
|
|
|
|
class Solution {
|
|
|
|
|
public:
|
|
|
|
|
int search(vector<int>& nums, int target) {
|
|
|
|
|
int left = 0;
|
|
|
|
|
int right = nums.size() - 1; // 定义target在左闭右闭的区间里,[left, right]
|
|
|
|
|
while (left <=
|
|
|
|
|
right) { // 当left==right,区间[left, right]依然有效,所以用 <=
|
|
|
|
|
int middle =
|
|
|
|
|
left + ((right - left) / 2); // 防止溢出 等同于(left + right)/2
|
|
|
|
|
if (nums[middle] > target) {
|
|
|
|
|
right = middle - 1; // target 在左区间,所以[left, middle - 1]
|
|
|
|
|
} else if (nums[middle] < target) {
|
|
|
|
|
left = middle + 1; // target 在右区间,所以[middle + 1, right]
|
|
|
|
|
} else { // nums[middle] == target
|
|
|
|
|
return middle; // 数组中找到目标值,直接返回下标
|
|
|
|
|
}
|
2022-11-21 12:04:27 +00:00
|
|
|
|
}
|
2022-11-24 08:44:36 +00:00
|
|
|
|
// 未找到目标值
|
|
|
|
|
return -1;
|
2022-11-21 12:04:27 +00:00
|
|
|
|
}
|
2022-11-24 08:44:36 +00:00
|
|
|
|
};
|
2022-11-21 12:04:27 +00:00
|
|
|
|
```
|
|
|
|
|
|
2022-11-24 08:44:36 +00:00
|
|
|
|
## 写法二
|
|
|
|
|
|
|
|
|
|
针对左闭右开(即 `[left, right)`):
|
2022-11-21 12:04:27 +00:00
|
|
|
|
|
|
|
|
|
```cpp
|
2022-11-24 08:44:36 +00:00
|
|
|
|
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; // 数组中找到目标值,直接返回下标
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
// 未找到目标值
|
2022-11-21 12:04:27 +00:00
|
|
|
|
return -1;
|
|
|
|
|
}
|
2022-11-24 08:44:36 +00:00
|
|
|
|
};
|
2022-11-21 12:04:27 +00:00
|
|
|
|
```
|
2022-11-24 08:44:36 +00:00
|
|
|
|
|
|
|
|
|
## 相关题目
|
|
|
|
|
|
2022-11-24 08:52:17 +00:00
|
|
|
|
- [704. 二分查找](https://leetcode.com/problems/binary-search/)
|
|
|
|
|
- [35. 搜索插入位置](https://leetcode.com/problems/search-insert-position/)
|
|
|
|
|
- [34. 在排序数组中查找元素的第一个和最后一个位置](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/)
|