154. Find Minimum in Rotated Sorted Array II(剑指offer)
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 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.
1 class Solution { 2 public int findMin(int[] a) { 3 if(a.length==0) return 0 ; 4 int left = 0,right = a.length-1,mid=0; 5 while(a[left]>=a[right]){ 6 if(right-left==1) return a[right]; 7 8 mid = left +(right-left)/2; 9 // 特殊处理[1 1 1 0 1] 10 // code 11 if((a[mid]==a[right])&&(a[mid]==a[left])) 12 return find_min(a,left,right); 13 // 14 if(a[left]<=a[mid]) left =mid; 15 if(a[right]>=a[mid])right = mid; 16 } 17 return a[mid]; 18 } 19 private int find_min(int[] a,int left,int right){ 20 int min = a[left]; 21 for(int i =left;i<=right;i++) 22 if(a[i]<min) 23 min =a[i]; 24 return min; 25 } 26 }