Find Minimum in Rotated Sorted Array II
LeetCode #154
Description:
Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed?
Would this affect the run-time complexity? How and why? 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).
Find the minimum element.
The array may contain duplicates.
Example:
Note
Idea:
这个与Search in Rotated Sorted ArrayII非常像,但是需要用[start, end] but not [start, end). 但update的方式几乎一样。
Time: O(n).
Code:
class Solution {
public:
int findMin(vector<int>& nums) {
int start=0;
int end=nums.size()-1;
while(start<end){
if(nums[start]<nums[end]) return nums[start];
int mid = start +(end-start)/2;
if(nums[start] < nums[mid]) start = mid+1;
else if(nums[start] > nums[mid]) end = mid;
else start++;
}
return nums[start];
}
};