Find Minimum in Rotated Sorted Array
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.
解题分析:基于有序数列,可以利用二分查找定位最小元素,即mid = start + end。
根据递增顺序划分情况:
1、nums[end] < nums[mid],最小值出现在mid-end之间,不包含mid;
2、nums[end] > nums[mid],最小值出现在start-mid间;
3、nums[end] == nums[mid],:
(1) end-start-mid为重复值,最小值出现在mid-end之间;
(2) mid-end为重复值,最小值出现在start-mid之间;
代码实现:
int findMin(vector<int>& nums) {
int start = 0, end = nums.size()-1;
while(start < end){
if(nums[start] < nums[end])return nums[start];
int mid = (start + end)/2;
if(nums[end] < nums[mid])
start = mid + 1;
else if(nums[end] > nums[mid])
end = mid;
else
end--;
}
return nums[start];
}