Find Minimum in Rotated Sorted Array II
Description
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.
Notice
The array may contain duplicates.
Example
Given [4,4,5,6,7,0,1,2] return 0.
Related problems
Find Minimum in Rotated Sorted Array
Medium Search in Rotated Sorted Array II
Implementation
Link: http://lintcode.com/en/problem/find-minimum-in-rotated-sorted-array-ii/
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
if(num.size() == 0) return -1;
int left = 0;
int right = num.size() - 1;
while(left + 1 < right){
int mid = left + (right - left)/2;
if(num[mid] == num[left]){
left++;
}else if(num[mid] == num[right]){
right--;
}else if(num[mid] > num[left]){
if(num[mid] < num[right]){
return num[left];
}else{
left = mid;
}
}else{ // num[mid] < num[left]
right = mid;
}
}
if(num[left] <= num[right]) return num[left];
if(num[right] < num[left]) return num[right];
return -1;
}
};