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.
旋轉數(shù)組是分為兩個有序數(shù)組,因此可以使用二分查找。
每次判斷一段數(shù)組是否有序,再根據(jù)有序部分首尾兩個數(shù)字和target的大小關系來判斷target存在于哪一部分。有序則調用正常二分,找不到則對剩下一半數(shù)組調用此函數(shù)。
class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
int res = -1, left = 0, right = n - 1;
while(left <= right)
{
int mid = (left + right) >> 1;
if(target == nums[mid])
{
res = mid;
break;
}
else if(nums[mid] < nums[right]) //后半部分有序
{
if(target > nums[mid] && target <= nums[right])
left = mid + 1;
else
right = mid - 1;
}
else //前半部分有序
{
if(target >= nums[left] && target < nums[mid])
right = mid - 1;
else
left = mid + 1;
}
}
return res;
}
};