leetcode之Find Minimum in Rotated Sorted Array II
阿新 • • 發佈:2018-12-16
問題描述如下:
Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?Would this affect the run-time complexity? How and why?
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.
問題連結cpp程式碼如下:
class Solution { public: int findMin(vector<int> &num) { if(num.size()==0)return -1; int l=0,h=num.size()-1; while(num[l]>=num[h]){ if(l+1==h) return num[h]; int m=l+(h-l)/2; if(num[l]==num[m]&&num[m]==num[h]){ int min_=num[l]; for(int i=l+1;i<=h;++i) if(min_>num[i])min_=num[i]; return min_; }else if(num[l]<=num[m]){ l=m; }else h=m; } return num[l]; } };