leetcode 之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.

思路: 该思路和Find Minimum in Rotated Sorted Array 一样,只是要注意A[start] = A[middle] = A[end], 此时最小值在两个区间内都是可能存在的。

class Solution {
public:
    int findMin(vector<int> &num) {
        int start = 0;  
        int end = num.size() - 1;  
        int middle;  
        while(start < end) {  
            //not reverse, return.  
            if(num[start] < num[end])  
                return num[start];  
            middle = (start + end )/ 2;  
            if(num[middle] > num[start])  
            {  
                start = middle + 1;  
            }else if (num[middle] < num[start]){  
                end = middle;  
                start += 1;  
            }else{
                start++;
            }  
        }  
        return num[end];  
    }
};


你可能感兴趣的:(LeetCode,array,sorted,rotated)