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).
Find the minimum element.You may assume no duplicate exists in the array.
Analysis
This problems seems like a binary search, and the key is how to break the array to two parts, so that we only need to work on half of the array each time, i.e., when to select the left half and when to select the right half.
If we pick the middle element, we can compare the middle element with the left-end element. If middle is less than leftmost, the left half should be selected; if the middle is greater than the leftmost, the right half should be selected. Using simple recursion, this problem can be solve in time log(n).
In addition, in any rotated sorted array, the rightmost element should be less than the left-most element, otherwise, the sorted array is not rotated and we can simply pick the leftmost element as the minimum.
注解:此题的关键就是搞清楚什么时候选择左半部分,什么时候选择右半部分。
class Solution {
private:
int helper(vector<int>& nums, int left, int right) {
if (left==right||nums[right]>nums[left]) {
return nums[left];
}
int mid = (left+right)/2;
if (nums[mid]<nums[left]) {
return helper(nums, left, mid); //注意,这里是保留mid的,因为mid可能是最小元素
} else {
return helper(nums, mid+1, right); //注意这里没有保留mid,因为mid一定不是最小元素
}
}
public:
int findMin(vector<int>& nums) {
int n = (int)nums.size();
return helper(nums, 0, n-1);
}
};