33. Search in Rotated Sorted Array
problem description
Suppose an array sorted in ascending order 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.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
algorithm thought
其实是二分查考的变种,一个有序数组,rotate之后数组一半还是顺序的。二分查找只要确定一半是否满足 就可以排除另一半。我们找到有序的一半之后,判断target是否期中,如果是就进入这一半查找否则进入另一半。这样每次排除一半,时间复杂度就是O(nlgn)
code
class Solution {
public:
int search(vector<int>& nums, int target) {
int left=0;int right=nums.size()-1;
int mid;
while(left<=right){
// cout<<left<<' '<<right<<';';
mid=(left+right)/2;
if(nums[mid]==target)
return mid;
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;
else
left=mid+1;
}
}
return -1;
}
};
algorithm thought
虽然循环中间处理比二分查找多很多步骤,但是时间复杂度还是O(1)的。每次排除一半,最后时间复杂度是O(nlgn)
Previous32. Longest Valid ParenthesesNext34. Find First and Last Position of Element in Sorted Array
Last updated