Friday, December 5, 2014

[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.
Analysis:
Similar to Find Minimum in Rotated Sorted Array, except that you need to take care of duplicate one.


int findMin(vector &num) {
        int b = 0;
        int e = num.size()-1;
        int minVal = num[0];
        while(b <= e)
        {
            int m = (b+e)/2;
            if (num[m] > num[b])
            {
                minVal = min(minVal, num[b]);
                b = m + 1;
            }
            else if (num[m] < num[e])
            {
                minVal = min(minVal, num[m]);
                e = m - 1;
            }
            else if (num[m] == num[e])
            {
                minVal = min(minVal, num[m]);
                e--;
            }
            else if (num[m] == num[b])
            {
                minVal = min(minVal, num[m]);
                b++;
            }
        }
        return minVal;        
    }

No comments:

Post a Comment