Leetcode: Find Minimum in Rotated Sorted Array II

来源:互联网 发布:彩票平台源码 编辑:程序博客网 时间:2024/03/29 22:03

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];    }};


0 0