leetcode154 - Find Minimum in Rotated Sorted Array II - hard

Suppose an array sorted in ascending order 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.

Example 1:

Input: [1,3,5]
Output: 1

Example 2:

Input: [2,2,2,0,1]
Output: 0

Note:

  • This is a follow up problem to Find Minimum in Rotated Sorted Array.
  • Would allow duplicates affect the run-time complexity? How and why?
 
存在duplicates的话,左半边并不是strictly大于右半边了。
或者说nums[l] == nums[m] == nums[r], m可以在左边这个区间,此时min在它右边;m也可以在右边这个区间,此时min在它左边。我们按既定操作来移动的话就错了。
leetcode154 - Find Minimum in Rotated Sorted Array II - hard_第1张图片
解决办法:
1. loop之前,while(nums[0] == nums[r] && r > 0) r--, 这样又是strictly大于了
2. loop里,如果nums[m] == nums[r], r左移一格,因为m取的floor是不会等于r的,说明在l到r-1区间里,肯定还有数等于nums[r]
 
实现1:
class Solution {
public:
    int findMin(vector<int>& nums) {
        
        if (nums.empty())
            return -1;
        
        int l = 0, r = nums.size()-1;
        while (nums[0] == nums[r] && r > 0)
            r--;
        while (l < r){
            int m = l + (r-l)/2;
            if (nums[m] <= nums[r])
                r = m;
            else
                l = m + 1;
        }
        
        return nums[r];
        
    }
};

 

实现2:

class Solution {
public:
    int findMin(vector<int>& nums) {
        
        if (nums.empty())
            return -1;
        
        int l = 0, r = nums.size()-1;
        while (l < r){
            int m = l + (r-l)/2;
            
            if (nums[m] == nums[r]){
                r--;
                continue;
            }
            
            if (nums[m] < nums[r])
                r = m;
            else
                l = m + 1;
        }
        
        return nums[r];
        
    }
};

 

你可能感兴趣的:(leetcode154 - Find Minimum in Rotated Sorted Array II - hard)