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.

思路:这种题目自己想给典型的,小点的例子来分析边界条件会比较快。不知道binary search是不是都这样的(:

12345

51234

45123

34512

23451

mid>high肯定在右边  更新low

mid<high不一定在左边,需要加个限制mid>low 更新high

while()的边界条件是low<high的原因是search 一个数,你最后的目的是让low==high,这样就找到那个唯一的数。

public class Solution {
    public int findMin(int[] nums) {
        int low=0;
        int high=nums.length-1;
        while(low<high)
        {
           int mid=low+(high-low)/2;
            if(nums[mid]<nums[high]&&nums[mid]>nums[low])
            {
                high=mid-1;
            }
            else if(nums[mid]>nums[high])
            {
               low=mid+1; 
            }
            else 
            {
                high=mid;
            }
        }
        return nums[high];
    }
}

 

posted on 2016-09-11 15:18  Machelsky  阅读(126)  评论(0编辑  收藏  举报