leetcode #154 in cpp

来源:互联网 发布:什么是网络公关 编辑:程序博客网 时间:2024/06/05 09:23

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.

Solution:

The difference between this question and the previous question is that the rule that works in the previous question does not work here:if nums[i] > nums[j] then nums[i...j] wouldn't contain the pivot and thus can be dropped. One example is [4,1,2,3,4], i = 0, j = 4. If we apply the rule above, then nums[0....4] is determined as having no pivot. But that is not true. Thus when we have num[left boundary] == num[right boundary], we cannot give up this range. Instead we shrink the left boundary or right boundary by skipping the duplicates. This step would introduce O(n) into our algorithm. 

Code:

class Solution {public:    int findMin(vector<int>& nums) {        int h = nums.size() - 1;        int l = 0;        int minn = INT_MAX;         while(h>=l){            int mid = (h+l)/2;             minn = min(nums[mid], minn);             if(nums[mid] <= nums[h]){                if(nums[mid] == nums[h]){                    while(h >= mid && nums[h] == nums[mid]){//skip duplicates                        h--;                     }                }else{                    minn = min(nums[mid], minn);                     h = mid - 1;                 }                            }else{                if(nums[mid] > nums[l]){                    minn = min(nums[l], minn);                    l = mid + 1;                 }else{                    while(l <= mid && nums[l] == nums[mid]){                        l++;                    }                }            }                    }        return minn;    }};


0 0
原创粉丝点击