Problem 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.
Example
Given [4, 5, 6, 7, 0, 1, 2] return 0
Note: You may assume no duplicate exists in the array.
Solution:
Apply binary search
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/** * @param num: a rotated sorted array * @return: the minimum number in the array */ public int findMin(int[] num) { int start = 0; int end = num.length - 1; if(num[start] < num[end]) return num[start]; while(start+1 < end) { int mid = start + (end - start)/2; if(num[start] <= num[mid]) { start = mid; } else { end = mid; } } return num[start] < num[end] ? num[start] : num[end]; } |