leetcode 154. Find Minimum in Rotated Sorted Array II

探讨了在允许重复元素的旋转有序数组中寻找最小值的问题。通过分析不同情况下的二分查找法,解决了在特定情况下算法实现的难点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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.

(这道题用二分查找需谨慎,注意以下几个测试用例):

 int[] nums=new int[]{1,3,3};
 int[] nums=new int[]{3,1,1};
 int[] nums=new int[]{3,1,3};
 int[] nums=new int[]{3,3,1,3};
我对于这道题二分查找的方法百思不得其解,只能用了最平凡的方法。
public int findMin(int[] nums) {
	if(nums.length==1){
		return nums[0];
	}
	for(int i=0;i<nums.length-1;i++){
		if(nums[i+1]<nums[i]){
			return nums[i+1];
		}
	}
	return nums[0];
}
大神就是用的二分查找的方法。

需要注意的是,这道题二分查找只能在 > 或者 < 时 二分。 当 = 时,会不清楚到底在左边还是右边,因此只能将 high-- 来缩小范围。

class Solution {
public:
    int findMin(vector<int> &num) {
        int lo = 0;
        int hi = num.size() - 1;
        int mid = 0;
        
        while(lo < hi) {
            mid = lo + (hi - lo) / 2;
            
            if (num[mid] > num[hi]) {
                lo = mid + 1;
            }
            else if (num[mid] < num[hi]) {
                hi = mid;
            }
            else { // when num[mid] and num[hi] are same
                hi--;
            }
        }
        return num[lo];
    }
};
When num[mid] == num[hi], we couldn't sure the position of minimum in mid's left or right, so just let upper bound reduce one.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值