[leetcode] 154. Find Minimum in Rotated Sorted Array II

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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.
  • Would allow duplicates affect the run-time complexity? How and why?

分析

题目的意思是:给你一个排序的数组,但是现在我们从某个位置开始,把数组的后半部分搬到前面,这样构成的数组就是rotated sorted array。然后找出这个数组里面最小的值。

  • 这是leetcode上的hard,我也做不出来,这里学习一下。

当数组中存在大量的重复数字时,就会破坏二分查找法的机制,我们无法取得O(lgn)的时间复杂度,又将会回到简单粗暴的O(n),比如如下两种情况:
{2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 1, 2} 和 {2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2}, 我们发现,当第一个数字和最后一个数字,还有中间那个数字全部相等的时候,二分查找法就崩溃了,因为它无法判断到底该去左半边还是右半边。这种情况下,我们将左指针右移一位,略过一个相同数字,这对结果不会产生影响,因为我们只是去掉了一个相同的,然后对剩余的部分继续用二分查找法,在最坏的情况下,比如数组所有元素都相同,时间复杂度会升到O(n)

代码

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

参考文献

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值