154. Find Minimum in Rotated Sorted Array II

1
2
3
4
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:

当有重复数字的时候,最差的情况会退化成O(N)的算法。在原来算法的基础上还要判断两个数字是否相等。如果相等的时候,只能排除掉一个数而不是一半的数字。
C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Solution {
public int findMin(int[] nums) {
if (nums == null || nums.length == 0) {
return Integer.MAX_VALUE;
}
int start = 0, end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[start] == nums[end]) {
start++;
} else if (nums[start] > nums[end]) {
if (nums[mid] < nums[end]) {
end = mid;
} else if (nums[mid] == nums[end]) {
end--;
} else {
start = mid;
}
} else {
// nums[start] < nums[end]
end = mid;
}
}
if (nums[start] <= nums[end]) {
return nums[start];
}
return nums[end];
}
}