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.
You may assume no duplicate exists in the array.
case1: mid > end 所以往mid右边找最小值
case2: mid < start mid左边找最小值
算法的时间复杂度变成O(n)
public class Solution { public int findMin(int[] num) { if (num == null || num.length == 0) { return -1; } int start = 0; int end = num.length - 1; int mid; while (start + 1 < end) { mid = (start + end) / 2; if (num[mid] >= num[end]) {//case 1 start = mid; } else {//case 2 end = mid; } } if (num[start] < num[end]) { return num[start]; } else { return num[end]; } } }
没有评论:
发表评论