1. 程式人生 > >#Leetcode# 154. Find Minimum in Rotated Sorted Array II

#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$ 結果就是這麼低的剛剛好爬過 看了一下題解 用的二分 現在還沒很懂但是先貼出來 一會肥宿舍的路上慢慢想

99% AC 程式碼(嫉妒臉):

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