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) {
if (nums.empty())
return -1;
//找到旋转点
int pivot = findPivot(nums , 0 , nums.size()-1);
int pos = binarySearch(nums, 0, pivot - 1, target);
if (pos != -1)
return pos;
else
pos = binarySearch(nums, pivot, nums.size() - 1, target);
return pos != -1 ? pos : -1;
}
//寻找旋转点
int findPivot(vector<int> &nums , const int &lhs , const int &rhs)
{
if (nums.empty() || lhs > rhs)
return -1;
int middle = (lhs + rhs) / 2;
//如果中间元素大于左侧首位值lhs,则旋转点要么在lhs要么在middle+1 ~ rhs
if (nums[middle] >= nums[lhs])
{
int pivot = findPivot(nums, middle + 1, rhs);
if (pivot == -1)
return lhs;
else if (nums[lhs] < nums[pivot])
return lhs;
else
return pivot;
}//反之,则旋转点要么在middle要么在lhs~middle-1
else{
int pivot = findPivot(nums, lhs, middle-1);
if (pivot == -1)
return middle;
else if (nums[middle] < nums[pivot])
return middle;
else
return pivot;
}//else
}
int binarySearch(vector<int> &nums, const int &lhs , const int &rhs ,int target)
{
if (nums.empty() || lhs > rhs)
return -1;
int middle = (lhs + rhs) / 2;
if (nums[middle] == target)
return middle;
else if (nums[middle] < target)
{
return binarySearch(nums, middle + 1, rhs, target);
}
else{
return binarySearch(nums, lhs, middle - 1, target);
}//else
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode(33)Search in Rotated Sorted Array
原文地址:http://blog.csdn.net/fly_yr/article/details/47980245