翻译
假定一个数组在一个我们预先不知道的轴点旋转。
例如,0 1 2 4 5 6 7可能会变为4 5 6 7 0 1 2。
给你一个目标值去搜索,如果找到了则返回它的索引,否则返回-1。
你可以假定没有重复的元素存在于数组中。
原文
Suppose a sorted array is rotated
at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search.
If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
代码
class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0, r = nums.size()-1;
while (l<=r) {
int mid = (r-l)/2+l;
if (nums[mid] == target)
return mid;
if (nums[mid] < nums[r]) {
if (nums[mid]<target && target<=nums[r])
l = mid+1;
else
r = mid-1;
} else {
if(nums[l]<=target && target<nums[mid])
r = mid-1;
else
l = mid+1;
}
}
return -1;
}
};