![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c962d3b5f7304c58364e5a82cedd5911.png)
题解
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/768e7ae0c9a7b9194d908099f0eb7546.png)
- 注意下标选取不要使用
m
i
d
−
1
或
m
i
d
+
1
mid - 1 或 mid + 1
mid−1或mid+1,避免越界
AC-Code
class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
if(n == 0) return -1;
if(n == 1) return nums[0] == target ? 0 : -1;
int L = 0, R = n - 1;
while(L <= R) {
int mid = L + (R - L >> 1);
if(nums[mid] == target) return mid;
if(nums[0] <= nums[mid]) {
if(nums[0] <= target && target < nums[mid]) {
R = mid - 1;
}
else {
L = mid + 1;
}
}
else {
if(nums[mid] < target && target <= nums[n - 1]) {
L = mid + 1;
}
else {
R = mid - 1;
}
}
}
return -1;
}
};