标签:
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.
首先因为新的array是由一个有序array轮转而来的,如果将这种array二分的话,可以预见有一半是sorted的了,另一半含有最小值。这样就找到了二分的条件和最后的循环停止条件。
public class Solution { public int findMin(int[] num) { int low = 0; int high = num.length-1; int mid =0; int min = Integer.MAX_VALUE; while(low <= high){ mid = (low+high)/2; if(num[mid] >= num[low]){ if(num[low]<min){ min=num[low]; } low=mid+1; } else{ if(num[mid] < min){ min=num[mid]; } high=mid-1; } } return min; } }
LeetCode-Find Minimum in Rotated Sorted Array
标签:
原文地址:http://www.cnblogs.com/incrediblechangshuo/p/4321285.html