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

LeetCode "Find Minimum in Rotated Sorted Array"

时间:2014-11-15 16:53:56      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   os   sp   for   

There‘s usually a common strategy for "find *" problems - binary search: half the space can be dropped by some rules.

And take care of corner cases.

bubuko.com,布布扣
class Solution 
{
    const int INVALID = std::numeric_limits<int>::min();

public:    
    int _findMin(vector<int> &num, int s, int e)
    {
        if (s == e) return num[s];
        if ((s + 1) == e)
        {
            return std::min(num[s], num[e]); // assumption on input
        }

        int mid = s + ((e - s) >> 1);
        if (num[s] <= num[mid] && num[mid + 1] <= num[e])
        {
            if (num[mid] < num[mid + 1])
            {
                return num[s];
            }
            else
            {
                return num[mid + 1];
            }
        }
        else if (num[s] <= num[mid])
        {
            return _findMin(num, mid + 1, e);
        }
        else
        {
            return _findMin(num, s, mid);
        }

        return INVALID;
    }

    int findMin(vector<int> &num) 
    {
        size_t len = num.size();
        return _findMin(num, 0, len - 1);
    }
};
View Code

 

LeetCode "Find Minimum in Rotated Sorted Array"

标签:style   blog   http   io   color   ar   os   sp   for   

原文地址:http://www.cnblogs.com/tonix/p/4099350.html

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