Find Minimum in Rotated Sorted Array II

Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

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) {
        int size = num.size();
        if (size < 1)
        {
            return -1;
        }

        int left = 0;
        int right = size - 1;
        while (left +1 < right)
        {
            int mid = left + (right-left)/2;
            bool chooseLeft = false;
            if (num[mid] <= num[right])
            {
                for (int i = left; i < mid; i++)
                {
                    if (num[i] < num[mid])
                    {   
                        chooseLeft = true;
                        break;
                    }
                }
            }
        
            if (chooseLeft)
            {   
                right = mid;
            }
            else
            {
                left = mid;
            }
        }

        if (num[left] <= num[right])
        {
            return num[left];
        }

        return num[right];
    }
};


你可能感兴趣的:(Find Minimum in Rotated Sorted Array II)