题目:
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.
解题思路:
在做过一定面试题的前提下,看到这种在一个与排序有关的数列里找某个数,应该有感觉与二分查找有关。
然后尝试一下一下可以发现,
如果数组的中位数大于末尾数,则最小数应该在后半段。
如果数组的中位数小于末尾数,则最小数应该在前半段或者是中位数。
代码如下
public int findMin(int[] num) { int low = 0, high = num.length - 1; while (low < high && num[low] >= num[high]) { int mid = (low + high) / 2; if (num[mid] > num[high]) low = mid + 1; else high = mid; } return num[low]; }