题目:
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) {
}
};
思路:
虽然不是所有元素都排序了的,但至少可以分成两部分,且两部分都是排好序的。因此我们还是可以用binary search方法来解。
但是怎样来进行取舍呢,即不能简单的根据target与中间元素的大小来决定是搜索左半边还是右半边。
注意到,不管上面的怎样旋转,我们取定中间元素后,一定有半边是严格排序的,比如:
6 7 0 1 2 4 5,我们取中间元素1,则右边是严格排序的,同样地
2 4 5 6 7 0 1,我们取中间元素6,则左边是严格排序的。
所以只需判断target是否在严格排序那边即可。
代码看起来比较复杂,其实很好理解,时间复杂度:O(lgn)
class Solution {
public:
int search(vector<int>& nums, int target) {
int size = nums.size();
if (size == 0) return -1;
int low = 0, high = nums.size() - 1;
return notBinary(nums, low, high, target);
}
int binary(vector<int>&nums, int low, int high,int target)
{
if (low == high && nums[low] == target) return low;
else if (low == high) return -1;
int mid = (low + high) / 2;
if (nums[mid] == target) return mid;
else if (nums[mid] > target&&mid>low) return binary(nums,low,mid-1,target);
else if(mid<high) return binary(nums,mid+1,high,target);
}
int notBinary(vector<int>&nums, int low, int high, int target)
{
if (low == (high - 1)) return nums[low] == target ? low : (nums[high] == target ? high : -1);
if (low == high && nums[low] == target) return low;
else if (low == high) return -1;
int mid = (low + high) / 2;
if (nums[mid] == target) return mid;
if (target >= nums[low] && target < nums[mid] &&mid>low) return binary(nums, low, mid - 1, target);
else if (target>nums[mid] && target <= nums[high] &&mid<high)
return binary(nums, mid+1, high, target);
else if (nums[low] < nums[mid] &&mid<high)
return notBinary(nums, mid + 1, high, target);
else if(mid>low) return notBinary(nums, low , mid-1, target);
else return -1;
}
};