154. Find Minimum in Rotated Sorted Array II (旋转重复数组二分查找最小值)
Hard
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 1:
Input: [1,3,5] Output: 1
Example 2:
Input: [2,2,2,0,1] Output: 0
1 class Solution { 2 public: 3 int findMin(vector<int>& nums) { 4 int low = 0; 5 int high = nums.size() - 1; 6 while(low < high) { 7 int mid = low + (high - low ) / 2; 8 if(nums[mid] < nums[high]) { 9 high = mid; 10 } else if (nums[mid] > nums[high]){ 11 low = mid + 1; 12 } else { // nums[mid] = nums[high] ,并不能确定nums[mid] 究竟在最小值的左侧还是右侧,因此我们不能莽撞地忽略某一部分的元素. 13 high--; 14 } 15 } 16 return nums[low]; 17 } 18 };
class Solution { public: int findMin(vector<int>& nums) { int low = 0; int high = nums.size()-1; while(low < high) { int mid = low + (high - low ) / 2; // 如果单调递增,如【1,2,3,4】 直接返回最小值。 if (nums[low] < nums[high]) return nums[low]; if(nums[low] > nums[mid]) { high = mid; } else if(nums[mid] > nums[low]) { low = mid+1; } else if (nums[mid] == nums[low]) { low+=1; } } return nums[low]; } };