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

LeetCode Find Minimum in Rotated Sorted Array

时间:2015-03-13 20:45:47      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:

1.题目


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.



2.解决方案


class Solution {
public:
    int findMin(vector<int> &num) {
        if(num[0] <= num[num.size() - 1]){
            return num[0];
        }
        
        int leftIndex = 0;
        int rightIndex = num.size() - 1;
        
        
        while((leftIndex + 1) < rightIndex){
            int midIndex = (leftIndex + rightIndex) / 2;
            if(num[midIndex] < num[leftIndex]){
                rightIndex = midIndex;
            }else{
                leftIndex = midIndex;
            }
        }
         return min(num[leftIndex], num[rightIndex]);
        
    }
};

思路:如果是N的时间复杂度肯定太慢了。可以用二分查找。这个跟二分查找的不同之处是,while里面的判断方式,这样可以留下两个数。因为我们也不知道究竟谁比较小。所以最后还要再找到最小的值。


http://www.waitingfy.com/archives/1630


LeetCode Find Minimum in Rotated Sorted Array

标签:

原文地址:http://blog.csdn.net/fox64194167/article/details/44245529

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