33.Search in Rotated Sorted Array
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.
这道题是典型的二分查找,由于没有重复元素,所以我们可以通过中间值和边缘值的大小关系来确定左右两半哪一半是有序的(或者说没有受到rotate的影响),确定之后,我们可以通过判断target是否存在于这个有序区间,若存在于其中,则在该区间上进行二分查找即可;若不存在,则在另一区间上进行二分查找,简而言之:
- 若A[mid]<A[high],则右半边有序,若target存在于此区间,则将low调整到mid+1处;否则,将high调整到mid-1
- 若A[mid]>=A[high],则左半边有序,若target存在于此区间,则将high调到mid-1处;否则,将low调整到mid+1处
- 若A[mid]==target,说明找到,返回
这个算法时间复杂度与Binary Search相同,O(lg n)
代码如下:
class Solution {
public:
int search(vector<int>& nums, int target) {
int size=nums.size(),low=0,high=size-1,mid=0;
while(low<=high){
mid=low+(high-low)/2;
if(target==nums[mid])
return mid;
if(nums[mid]<nums[high]){
if(target>nums[mid]&&target<=nums[high])
low=mid+1;
else
high=mid-1;
}
else{
if(target>=nums[low]&&target<nums[mid])
high=mid-1;
else
low=mid+1;
}
}
return -1;
}
};