int search(vector<int>& nums, int target) {
int n = nums.size();
if (n == 1) {
if (target == nums[0]) {
return 0;
}
else {
return -1;
}
}
int l = 0, r = n - 1;
int mid;
int xzd = 0;
while (l <= r) {
mid = l + (r - l) / 2;
if (mid+1<n&&nums[mid] < nums[mid + 1]) {
if (nums[mid] >= nums[0]) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
else {
xzd = mid;
break;
}
}
if (target < nums[0]) {
l = xzd + 1; r = n - 1;
}
else {
l = 0; r = xzd;
}
while (l <= r) {
mid = l + (r - l) / 2;
if (nums[mid] < target) {
l = mid + 1;
}
else if (nums[mid] > target) {
r = mid - 1;
}
else {
return mid;
}
}
return -1;
}
如果要在logn时间内解决,需要用两次二分法。一次用来找旋转点,另一次找target。