[LeetCode]Find Minimum in Rotated Sorted Array II

探讨了在允许重复元素的旋转排序数组中寻找最小值的问题。通过改进二分查找法,解决了因重复元素导致的时间复杂度问题。

Question

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 a sorted array 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.


本题难度Hard。

二分查找法

【复杂度】
时间 O(N) 空间 O(N) 递归栈空间

【思路】
这道题难点就在于有重复数。[LeetCode]Find Minimum in Rotated Sorted Array的思路差不多,其实只要增加对于nums[r]==nums[mid]的情况处理:让r向左移动,直到mid==r||nums[r]!=nums[mid],然后再继续递归即可。中心思路就是抛弃多余的重复数(不是全部抛弃,有可能重复数就是最小值)。

【代码】

public class Solution {
    public int findMin(int[] nums) {
        return helper(0,nums.length-1,nums);
    }
    private int helper(int l,int r,int[] nums){
        //base case
        if(r==l)return nums[l];

        int mid=(l+r)/2;
        if(nums[r]>nums[mid])return helper(l,mid,nums);
        //addtional case
        if(nums[r]==nums[mid]){
            while(mid!=r&&nums[r]==nums[mid])r--;
            return helper(l,r,nums);
        }else
            return helper(mid+1,r,nums);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值