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

Find Minimum in Rotated Sorted Array——LeetCode

时间:2015-04-22 13:30:51      阅读:96      评论: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.

题目大意:给定一个有序数组,是经过旋转过的,不知道在哪儿旋转的,求数组最小元素。

解题思路:直接遍历可以,太low。二分搜索吧,有序数组旋转有个特征,旋转后面的元素比旋转点前面的所有元素都小。

Talk is cheap>>

    public int findMin(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int low = 0;
        int high = nums.length - 1;
        int mid = 0;
        while (low <= high) {
            mid = (low + high) >> 1;
            int left = mid > 0 ? mid - 1 : 0;
            int right = mid < nums.length - 1 ? mid + 1 : nums.length - 1;
            if (nums[mid] <= nums[left] && nums[mid] <= nums[right]) {
                break;
            }
            if (nums[mid] >= nums[high]) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return nums[mid];
    }

 

Find Minimum in Rotated Sorted Array——LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4447068.html

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