leetcode 153|154. Find Minimum in Rotated Sorted Array 1|2

来源:互联网 发布:市场份额数据优缺点 编辑:程序博客网 时间:2024/06/07 21:31

153. 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.

二分查找

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

154. Find Minimum in Rotated Sorted Array II

Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

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.


可能有重复。那就加两句话

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