leetcode #154 in cpp

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章