Suppose an array sorted in ascending order 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.
You may assume no duplicate exists in the array.
Example 1:
Input: [3,4,5,1,2]
Output: 1
Example 2:
Input: [4,5,6,7,0,1,2]
Output: 0
题意:
如题
Solution: Binary Search
code
1 class Solution { 2 public int findMin(int[] num) { 3 if (num == null || num.length == 0) { 4 return 0; 5 } 6 if (num.length == 1) { 7 return num[0]; 8 } 9 int start = 0, end = num.length - 1; 10 while (start < end) { 11 int mid = (start + end) / 2; 12 if (mid > 0 && num[mid] < num[mid - 1]) { 13 return num[mid]; 14 } 15 if (num[start] <= num[mid] && num[mid] > num[end]) { 16 start = mid + 1; 17 } else { 18 end = mid - 1; 19 } 20 } 21 return num[start]; 22 } 23 }