class Solution {
public:
int search(vector<int>& nums, int target) {
int n = (int)nums.size();
if (!n) {
return -1;
}
if (n == 1) {
return nums[0] == target ? 0 : -1;
}
int l = 0, r = n - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (nums[mid] == target) return mid;
//[0,mid]区间有序
if (nums[0] <= nums[mid]) {
//target在[0,mid)区间
if (nums[0] <= target && target < nums[mid]) {
r = mid - 1;
} else {
l = mid + 1;
}
} else {
//[0,mid]区间不是有序
if (nums[mid] < target && target <= nums[n - 1]) {
//target在[mid+1,n-1]区间
l = mid + 1;
} else {
//target在[0,mid-1]区间
r = mid - 1;
}
}
}
return -1;
}
};