题目:Suppose a sorted array is rotatedat some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 01 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 thearray.
翻译
假定一个数组在一个我们预先不知道的轴点旋转。
例如,0 1 2 4 5 6 7可能会变为4 5 6 7 0 1 2。
给你一个目标值去搜索,如果找到了则返回它的索引,否则返回-1。
你可以假定没有重复的元素存在于数组中。
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;
}
};
法二:
class Solution {
public:
int search(int A[], int n, int target) {
int lo = 0, hi = n - 1;
// 找到最小值的索引
while (lo<hi){
int mid = (lo + hi) / 2;
if (A[mid]>A[hi]) lo = mid + 1;
else hi = mid;
}
// lo==hi是最小值的索引也是数组旋转的位置
int rot = lo;
lo = 0; hi = n - 1;
// 使用二分查找
while (lo <= hi){
int mid = (lo + hi) / 2;
int realmid = (mid + rot) % n;
if (A[realmid] == target) return realmid;
if (A[realmid]<target)lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
};