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
解题思路
本题采用递归的写法,类似归并排序,将数组的子区间的长度逐次减半。
- 当子区间的长度 <= 2时,返回一(或两)个元素之间的较小值
- 递归寻找左边区间的最小的数 minl
- 递归寻找右边区间的最小的数 minr
- 返回 minl 和 minr 之间的较小值
这种方法允许数组中出现重复元素的情况
C++代码
class Solution {
public:
int findMin(vector<int>& nums) {
return loop(nums, 0, nums.size()-1);
}
int loop(vector<int>& nums, int left, int right) {
if(right - left <= 1) {
return min(nums[left], nums[right]);
}
int minl = loop(nums, left, (left + right) / 2);
int minr = loop(nums, (left + right) / 2 + 1, right);
return min(minl, minr);
}
};