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

leetcode_154_Find Minimum in Rotated Sorted Array II

时间:2015-03-11 14:57:45      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   binary search   

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢技术分享


154 Find Minimum in Rotated Sorted Array II 

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.

The array may contain duplicates.


//方法一:正常的解法
class Solution {
public:
    int findMin(vector<int> &num) {
        if( num.size()==0 )
            return NULL;
        int length = num.size();
        int left = 0;
        int right = length-1;
        int mid = left;
        
        while( num[left] >= num[right])
        {
            if( right-left == 1)
            {
                mid = right;
                break;
            }
            
            mid = (left+right)/2;
            if( num[left]==num[right] && num[left]==num[mid] )
            {
                int result = num[left];
                for( int i=left+1 ; i<=right; i++)
                {
                    if( result > num[i] )
                        result = num[i];
                }
                return result;
            }
            
            if( num[left] <= num[mid] )
                left = mid;
            else if ( num[right] >= num[mid] )
                right = mid;
        }
        
        return num[mid];
    }
};


//方法二:网上方法,记住前面的方法即可
class Solution {
public:
    int findMin(vector<int> &num) {
        if( num.size()==0 )
            return NULL;
        int length = num.size();
        int left = 0;
        int right = length-1;
        
        while( left<right )
        {
            int mid = (left+right)/2;
            if( num[left] == num[right] )
                left++;
            else if ( num[left] < num[right] )
                break;
            else
            {
                if( num[left] <= num[mid])
                    left = mid+1;
                else if ( num[right] >= num[mid] )
                    right = mid;
            }
        }
        return num[left];
    }
};



leetcode_154_Find Minimum in Rotated Sorted Array II

标签:leetcode   c++   binary search   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/44197107

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