Skip to content

153. Find Minimum in Rotated Sorted Array

153. Find Minimum in Rotated Sorted Array

难度:Medium

内容

题目链接:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array

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.

You may assume no duplicate exists in the array.

Example 1:

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

Example 2:

Input: [4,5,6,7,0,1,2]
Output: 0

思路

最简单的方法,挨个遍历,如果当前值小于前一个值,那么输出当前值即可,时间复杂度为O(n)。 二分查找法,时间复杂度为O(log(n))。

代码

快速简单的写了一个,提交,过了。

class Solution {
public:
    int findMin(vector<int>& nums) {
        int res_idx = 0;
        for (int i = 1; i < nums.size(); ++i)
            if (nums[i] < nums[i-1]) {
                res_idx = i;
                break;
            }
        return nums[res_idx];
    }
};

二分查找的简单实现

class Solution {
public:
    int findMin(vector<int>& nums) {
        int left = 0, right = nums.size() - 1;
        while (nums[left] > nums[right]) {
            int mid = (right + left) >> 1;
            if (nums[mid] >= nums[left])
                left = mid + 1;
            else
                right = mid;
        }
        return nums[left];
    }
};

用迭代器来实现

class Solution {
public:
    int findMin(vector<int>& nums) {
        auto begin = nums.begin();
        auto end = std::prev(nums.end());
        while (*begin > *end) {
            auto gap = (end - begin) >> 1;
            *next(begin, gap) >= *begin ? advance(begin, gap + 1) : advance(end, -gap); 
        }
        return *begin;
    }
};

来源:https://github.com/xiaqunfeng/leetcode



回到顶部