题目:
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.
思路:
二分法,让 left = right 时 输出答案。遇到重复项 left++ 或者 right--。时间复杂度 O(logn)~O(n)
Code:
public int findMin(int[] num) {
if(num.length==0) return 0;
if(num.length==1) return num[0];
int left=0, right=num.length-1;
int mid,min;
while(left<right){
mid=(left+right)/2;
if(num[left]<num[mid]){
if(num[right]>num[left]) return num[left];
left=mid;
}
else if(num[mid]<num[right]) right=mid;
else{
if(num[left]==num[mid]) left++;
if(num[mid]==num[right]) right--;
}
}
return num[left];
}
备注: