Find Minimum in Rotated Sorted Array II
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.
http://www.lintcode.com/en/problem/find-minimum-in-rotated-sorted-array-ii/
Discussion
存在重复元素,那么跟Find Minimum in Rotated Sorted Array问题相比,if(num[mid] == num[end]) end--
;即可。注意不是start++,因为会跳过最小值了。
这个题跟Search in Rotated Sorted Array 问题扩展到Search in Rotated Sorted Array II问题的思路是一样的。
Solution
class Solution {
public:
/**
* @param num: the rotated sorted array
* @return: the minimum number in the array
*/
int findMin(vector<int> &num) {
// write your code here
int start = 0;
int end = num.size() -1;
while(start + 1 < end) {
int mid = start+ (end-start)/2;
if(num[mid] < num[end]) {
end = mid;
} else if(num[mid] > num[end]) {
start = mid;
} else {
end--;
}
}
if(num[start]<=num[end]) return num[start];
return num[end];
}
};