#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <unordered_map>
#include <utility>
#include <algorithm>
using namespace std;
// 二分法代码模板1,注意区间划分
class Solution
{
public:
// 方法1:定义target在左闭右闭的区间[left, right]
int search(vector<int> &nums, int target)
{
int left = 0, right = nums.size() - 1;
while (left <= right)
{ // 当left==right,区间[left, right]依然有效,所以用<=
int mid = left + ((right - left) / 2); // 防止溢出 等同于(left + right)/2
if (nums[mid] > target)
{
right = mid - 1; // target在左区间[left, mid-1]中
}
else if (nums[mid] < target)
{
left = mid + 1; // target在右区间[mid+1, right]中
}
else
return mid; // 数组中找到目标值,直接返回下标
}
return -1; // 未找到
}
};
// 二分法代码模板2,注意区间划分
class Solution
{
public:
// 方法2:定义target在左闭右开的区间[left, right)
int search(vector<int> &nums, int target)
{
int left = 0, right = nums.size();
while (left < right)
{ // 因为left == right的时候,在[left, right)是无效的空间,所以使用<
int mid = left + ((right - left) >> 1);
if (nums[mid] > target)
{
right = mid; // target在左区间[left, mid)中
}
else if (nums[mid] < target)
{
left = mid + 1; // target在右区间[mid+1, right)中
}
else
return mid; // 数组中找到目标值,直接返回下标
}
return -1; // 未找到
}
};
07-08
219
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-27
388
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-20
522
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-20
393
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)