Find Minimum in Rotated Sorted Array II
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.
O(n)的方法
找到有序的一边。然后取min就可以。
关键就是找到rotate list有序的那一边
循环实现:
class Solution { public: int findMin(vector<int> &num) { return find(num,0,num.size()-1); } int find(vector<int> &num,int left,int right){ if(left==right) return num[left]; int mi = INT_MAX; while(left<=right){ int mid = (left+right)/2; int i=mid,j=mid; while(i>=left && num[i]==num[mid]) i--; while(j<=right && num[j]==num[mid]) j++; mi = min(mi,num[mid]); if(i<left){ if(j>right){ break; }else left = j; }else{ if(j>right) right = i; else{ if(num[left]<=num[i]){ mi = min(num[left],mi); left = j; }else{ mi = min(num[j],mi); right = i; } } } } return mi; } };
递归实现:
class Solution { public: int findMin(vector<int> &num) { return find(num,0,num.size()-1); } int find(vector<int> &num,int left,int right){ if(left==right) return num[left]; int mid = (left+right)/2; int i=mid,j=mid; while(i>=left && num[i]==num[mid]) i--; while(j<=right && num[j]==num[mid]) j++; if(i<left){ if(j>right) return num[mid]; return min(num[mid],find(num,j,right)); }else{ if(j>right) return min(num[mid],find(num,left,i)); if(num[left]<=num[i]){ return min(num[mid],min(num[left],find(num,j,right))); }else{ return min(num[mid],min(num[j],find(num,left,i))); } } } };
posted on 2017-07-25 12:49 cynchanpin 阅读(148) 评论(0) 编辑 收藏 举报