题目
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.
解析
class Solution {
public int findMin(int[] a) {
int n = a.length;
if (n == 0) {
return 0;
} else if (n == 1) {
return a[0];
} else if (n == 2) {
return Math.min(a[0], a[1]);
}
int left = 0, right = n - 1;
while (left < right - 1) {
if (a[left] < a[right]) {
return a[left];
}
int mid = (left + right) >> 1;
if (a[left] < a[mid]) {
left = mid;
} else if (a[left] > a[mid]) {
right = mid;
} else {
left++;
}
}
return Math.min(a[left], a[right]);
}
}