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).
Example
Given [4,4,5,6,7,0,1,2]
return 0
.
public class Solution {
/**
* @param num: a rotated sorted array
* @return: the minimum number in the array
*/
public int findMin(int[] num) {
int left = 0, right = num.length - 1;
while(left + 1 <= right && num[left] == num[left + 1]) left++;
while(left + 1 <= right && num[right] == num[right - 1]) right--;
while(left < right) {
if(num[left] < num[right]) return num[left];
int mid = (left + right) / 2;
if (num[left] <= num[mid]) {
left = mid + 1;
while(left + 1 <= right && num[left] == num[left + 1]) left++;
} else {
right = mid;
while(left + 1 <= right && num[right] == num[right - 1]) right--;
}
}
return num[left];
}
}