地址
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/
题目
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
Note:
- This is a follow up problem to Find Minimum in Rotated Sorted Array.
- Would allow duplicates affect the run-time complexity? How and why?
思路
对于rotate后的数组,里面的元素大概长这样[5,5,5,6,7,...,1,2,3,4,5,5,5,5](数组内可能有重复元素),所以数组中最小元素a[i]显然是第一个大于a[0]的数。
可以看出,a[i]左边的元素都大于等于a[0],a[i]及a[i]右边的元素都小于等于a[0]。所以我们可以通过二分查找i。
但是由于a[i]的左右两边都存在可能等于a[0]的元素,二分时不好区分,所以要先处理掉数组最右边和a[0]相等的元素(也就是修改二分的上界)。
代码
class Solution {
public:
int findMin(vector<int>& a) {
if(a.size()==1) return a[0];
int l=1,r=a.size()-1;
while(r>1&&a[r]==a[0]) --r;
if(r==0||a[r] > a[0]) return a[0];
while(l<r)
{
int mid=l+r>>1;
if(check(mid, a))
l=mid+1;
else
r=mid;
}
return a[r];
}
bool check(int x, vector<int>& a)
{
return a[x]>=a[0];
}
};