题目链接:Find Minimum in Rotated Sorted Array II
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.
You may assume no duplicate exists in the array.
这道题的要求是在旋转数组中找到最小值。
一道在旋转数组中搜索的题目,和Search in Rotated Sorted Array和Search in Rotated Sorted Array II同样在旋转数组中搜索的题目,不过这个找最小值相对于找指定元素会容易些吧。
同时这道题比Find Minimum in Rotated Sorted Array多一种情况,就是元素相等。也就是说,在num[l] = num[m] = num[r]的时候,最小元素可能在m的左侧也可能在m的右侧,因此令l右移一位。例如[1, 1, 1, 0, 1]这组数据,这种情况下,最差时间复杂度降低为O(n)。
时间复杂度:O(logn)
空间复杂度:O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution
{
public:
int findMin(vector<int> &num)
{
int l = 0, r = num.size() - 1;
while(l < r && num[l] >= num[r])
{
int m = (l + r) / 2;
if(num[m] > num[r])
l = m + 1;
else if(num[m] < num[l])
r = m;
else // num[l] = num[m] = num[r]
++ l;
}
return num[l];
}
};