#Leetcode# 154. Find Minimum in Rotated Sorted Array II

时间:2021-12-04 04:26:48

https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/

 

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.(这里是我的 code 嘻嘻嘻)

  • Would allow duplicates affect the run-time complexity? How and why?

代码:

class Solution {
public:
    int findMin(vector<int>& nums) {
        if(nums.empty()) return 0;
        int n = nums.size();
        set<int> s;
        for(int i = 0; i < n; i ++)
            s.insert(nums[i]);
        
        set<int>::iterator ans = s.begin();
        return *ans;
    }
};

  #Leetcode# 154. Find Minimum in Rotated Sorted Array II

因为说有的数字会重复就直接想到了 $set$ 结果就是这么低的刚刚好爬过 

#Leetcode# 154. Find Minimum in Rotated Sorted Array II#Leetcode# 154. Find Minimum in Rotated Sorted Array II
class Solution {
public:
    int findMin(vector<int>& nums) {
        int i = 0, j = nums.size()-1;
        while(i < j){
           int mid = (i + j) / 2;
            if((nums[mid] > nums[i] && nums[mid] <= nums[j])
               || nums[mid] >= nums[i] && nums[mid] < nums[j])
                j = mid - 1;
            else if(nums[i] <= nums[mid] && nums[mid] > nums[j])
                i = mid + 1;
            else if(nums[i] > nums[mid] && nums[mid] <= nums[j])
                j = mid;
            else{
                i ++, j --;
            }
        }
        return nums[i];
    }
};