Leetcode: 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.

如果有重复,时间复杂度可能退化到O(n),因为不能确定最小元素在中点的哪一侧。

class Solution {
public:
    int findMin(vector<int> &num) {
        int left = 0;
        int right = num.size() - 1;
        int mid;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (num[mid] > num[left]) {
                if (num[left] >= num[right]) {
                    left = mid + 1;
                }
                else {
                    right = mid;
                }
            }
            else if (num[mid] == num[left])
            {
                if (num[mid] > num[right]) {
                    left = mid + 1;
                }
                else if (num[mid] == num[right]) {
                    ++left;
                }
                else {
                    return num[mid];
                }
            }
            else {
                right = mid;
            }
        }
        
        return num[right];
    }
};


你可能感兴趣的:(二分查找,折半查找)