leetcode_154_Find Minimum in Rotated Sorted Array II

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢微笑


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,C++,search,binary)