leetcode Find Minimum in Rotated Sorted Array II

和上题一样,这里要求可以重复数字。那么需要考虑的就比较多一步了。

如果中间的值和左边的值相等的话,并且中间下标不等于左边下标的话,那么就存在问题了,因为我们不知道最小的到底会出现在哪里。那么就只能left++,继续判断了,所以最坏情况还是O(n)

只要在上题基础上,稍微修改一下就行了。

class Solution {

public:

    int findMin(vector<int> &num)

    {

        int len = num.size(), left = 0, right = len - 1, mid = (left + right ) / 2, minmum = INT_MAX;

        while(left != right)

        {

            mid = (left + right) / 2;

            if (num[mid] == num[left])

            {

                if (mid == left)

                {

                    if (num[left] > num[right])

                        left = right;

                    break;

                }

                left++; // 这里和上题不一样

            }

            else if (num[mid] > num[left])

            {

                if (num[left] < minmum) minmum = num[left];

                left = mid + 1;

            }

            else if (num[mid] < num[left])

            {

                if (num[mid] < minmum) minmum = num[mid];

                right = mid - 1;

            }

        }

        minmum = min(minmum, num[left]);

        return minmum;

    }

};

 

2015/03/29:

python:

class Solution:

    # @param num, a list of integer

    # @return an integer

    def findMin(self, num):

        left, right = 0, len(num) - 1

        while left < right:

            mid = (left + right) / 2

            if num[mid] > num[right]:

                left = mid + 1

            elif num[mid] < num[right]:

                right = mid

            else:

                right -= 1

        return num[left]

 

你可能感兴趣的:(LeetCode)