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.
The array may contain duplicates.
分析:
这个题目中最小值可能出现在三个位置:
1. 最左边,这时数组没有出现乱序;
2. 左半段,但不是最左,这时左半部分是乱序的,右边是有序的,应查找左半段;
3. 右半段,这时左半段是有序的,查找右半段;
代码如下:
class Solution {
public:
int findMin(vector<int>& nums) {
int n= nums.size();
int low=0,high=n-1,mid;
while(low<high)
{
mid = (low+high)/2;
if(nums[low]<nums[high]) return nums[low];
if(nums[low]<nums[mid]) low = mid+1;
else if(nums[low]>nums[mid]) high = mid;
else low++;
}
return nums[low];
}
};