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.
The array may contain duplicates.
分析:此题的难点在于duplicate的处理,最坏情况(全部是相同数)时间复杂度是O(n)。此题在实现过程中,返回条件跟Find Minimum in Rotated Sorted Array I不同,优点是不会漏掉一些特殊情况且易于理解。因为这里我们搜索的是最小元素,所以我们不断缩小l,r指针的范围,知道l = r或者l = r-1时便可以轻松的求出最小值。并且要特别注意数组没有被rotated的情况。
总而言之,解决这道问题需要解决以下几点:
1)如何判断当前元素为最小值 2) 在有重复元素的情况下如何更新左指针和右指针。
代码如下:
1 class Solution { 2 public: 3 int findMin(vector<int> &num) { 4 int n = num.size(); 5 int l = 0, r = n-1; 6 if(num[0] < num[n-1]) return num[0];//for no-rotatin case 7 8 while(l <= r){ 9 if(l == r) return num[l]; 10 if(l == r - 1) return min(num[l], num[r]); 11 int mid = (l + r)/2; 12 if(num[mid] > num[0]) 13 l = mid + 1; 14 else if(num[mid] < num[0]) 15 r = mid;//take more notice here, because mid may be the minimum 16 else if(num[0] > num[n-1]) 17 l = mid + 1; 18 else{ 19 int tmp = mid; 20 while(tmp < n - 1 && num[tmp] == num[tmp + 1]){ 21 tmp++; 22 } 23 if(tmp == n-1)//if from mid to n-1 are all the same 24 r = mid;//take more notice here, because mid may be the minimum 25 else l = tmp; 26 } 27 28 } 29 } 30 };