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

Posted 丧心病狂工科女

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#Leetcode# 154. Find Minimum in Rotated Sorted Array II相关的知识,希望对你有一定的参考价值。

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

  

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

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

以上是关于#Leetcode# 154. Find Minimum in Rotated Sorted Array II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 154.Find Minimum in Rotated Sorted Array II

leetcode 154. Find Minimum in Rotated Sorted Array II --------- java

LeetCode OJ 154. Find Minimum in Rotated Sorted Array II

Leetcode.154.Find Minimum in Rotated Sorted Array II

leetcode-Find Minimum in Rotated Sorted Array II-154

[LeetCode] 154. Find Minimum in Rotated Sorted Array II 寻找旋转有序数组的最小值 II