LeetCode 154. Find Minimum in Rotated Sorted Array II (Hard)

Find Minimum in Rotated Sorted Array II

Description

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.

Subscribe to see which companies asked this question.

Analysis
这道题目给出来的函数为 int findMin(vector& nums),所以所给序列是以向量的形式给出,而向量里面每一个值的表示是可以用数组的形式来表示的。
对于这道题目,由于给出来的是旋转的有序序列,所以我认为最好的方法就是利用二分法,通过每一个二分比较去掉有序并且不包含最小数的那一部分。
所以我就按照这二分法的形式写了,但是出现了wrong answer的错误。然后我发现这道题目中的序列可能包含重复的数所以我的代码不能判断应该去掉哪一部分。所以我进行了修改,就是当相同时,使low(左边)移动一步再进行比较。

Code

class Solution {
public:
    int findMin(vector<int>& nums) {
        int len = nums.size();
        int low = 0;
        int high = nums.size( ) - 1;
        int result = nums[0] ;

        while(low < high){
            int mid = (low + high)/2;

            if(nums[mid] > nums[low]){
                result = min(nums[low] , result);
                low = mid + 1;
            } 

            else if(nums[mid] < nums[low]){
                result = min(nums[mid] , result);
                high = mid - 1;
            }

            else{
                result = min(result , nums[low]);
                low++;
            } 
        } 
        result = min(nums[low],result);
        result = min(nums[high],result);
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值