题目:数组
Suppose a sorted array is rotated at some pivot unknown to you beforehand.spa
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).code
Find the minimum element.blog
You may assume no duplicate exists in the array.element
解题思路:
class
首先假设一个sorted没有rotated的数组[1,2,3],假设咱们经过一个pivot把这个数组rotate,那么结果可能为:[2,3,1], [3,1,2], 能够发现:num[low]永远大于(或等于)num[high]。由于你以前是sorted的数组,你在一个sorted的数组找了一个pivot进行rotate,那么好比pivot后面的值都大于pivot以前的值。因此依据这个发现,以及二分法查找。咱们能够根据如下判断来解题。num[mid]有两种可能性,若是num[mid] > num[high],证实num[mid]在rotated后的那个区间内,这个区间咱们刚才已知都大于pivot以前的值,因此最小值就在low=mid+1那个区间内。另外一种可能,num[mid] <= num[high],那么咱们刚才能够看出来这种可能性说明mid~high以及是排好序的,那么最小值在high=mid这个区间内(mid多是最小值)。依据此判断能够找到最小值。
im
代码以下:sort