美文网首页
153. Find Minimum in Rotated Sor

153. Find Minimum in Rotated Sor

作者: exialym | 来源:发表于2016-09-23 13:06 被阅读8次

    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.

    我们来观察一下:
    01234
    12340
    23401
    34012
    40123
    如果中间的值大于左边和右边的,那我们要找的在右边
    如果中间值小于左边的和右边的,那我们要找的在左边
    如果中间值大于左边小于右边的,那左边的就是我们要找的

    var findMin = function(nums) {
        var left = 0;
        var right = nums.length - 1;
        while (left<right) {
            var mid = left + parseInt((right - left) / 2);
            if (nums[mid]>=nums[left]&&nums[mid]>=nums[right]) 
                left = mid + 1;
            else if (nums[mid]<=nums[left]&&nums[mid]<=nums[right]) 
                right = mid;
            else if (nums[mid]>=nums[left]&&nums[mid]<=nums[right]) 
                return nums[left];
        }
        return nums[left];
    };
    

    相关文章

      网友评论

          本文标题:153. Find Minimum in Rotated Sor

          本文链接:https://www.haomeiwen.com/subject/gwdtyttx.html