leetcode 33. Search in Rotated Sorted Array
题目意思
给你一个有序数组,然后翻转成为这样的数组[5, 6, 7, 8, 9, 0, 1, 2, 3]
然后寻找target的下标,没有就返回-1
我们就每次不断判断当前值和nums[0]的关系,如果 nums[m] 和 target在一个区间,那么就正常二分
否则,如果nums[m] >= nums[0] 但 target < nums[0] 这样子,我们就把l 右移,这样等 target和nums[m] 同样区间的时候再正常二分
题解
class Solution {
public:
int search(vector<int>& nums, int target) {
int len = nums.size();
if(len == 0 || (len == 1 && nums[0] != target)) return -1;
if(len == 1 && nums[0] == target) return 0;
int l = 0, r = len - 1;
int ans = -1;
while(l <= r) {
int m = (l+r)/2;
// cout << l <<" " << r << " " << nums[m]<<endl;
bool a = (nums[m] >= nums[0]) ^ (target >= nums[0]);
// cout << a <<endl;
if(!a) {
if(nums[m] >= target) {
ans = m;
r = m-1;
} else
l = m+1;
} else if(target >= nums[0]) {
r = m-1;
} else {
l = m+1;
}
}
if(ans != -1 && nums[ans] == target)
return ans;
return -1;
}
};