码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-Find Minimum in Rotated Sorted Array

时间:2015-03-08 13:01:14      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!