Find Minimum in Rotated Sorted Array II
- leetcode: Find Minimum in Rotated Sorted Array II | LeetCode OJ
- lintcode:
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
The array may contain duplicates.
Example
题解
由于此题输入可能有重复元素,因此在时无法使用二分的方法缩小start或者end的取值范围。此时只能使用递增start/递减end逐步缩小范围。
public class Solution {
* @param num: a rotated sorted array
* @return: the minimum number in the array
*/
public int findMin(int[] num) {
if (num == null || num.length == 0) return Integer.MIN_VALUE;
// case1: num[0] < num[num.length - 1]
// if (num[lb] < num[ub]) return num[lb];
// case2: num[0] > num[num.length - 1] or num[0] < num[num.length - 1]
int mid = lb + (ub - lb) / 2;
if (num[mid] < num[ub]) {
ub = mid;
lb = mid;
} else {
ub--;
}
}
return Math.min(num[lb], num[ub]);
最坏情况下 O(n), 平均情况下 O(\log n).