154. Find Minimum in Rotated Sorted Array II(Binary search)

https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/description/ -- leetcode

follow up question: find the minimum element in a rotated array with duplicate elements

Idea: [3,3,1,3] compared to [3,4,1,2]  -> l = mid+1 --1

         [1,3,3] compared to [1,3,4] - > r = mid;  -- 2

         If we used the previous solution, it will complain with the above cases because one case is : nums[mid] > nums[r] l = mid+1; violating the 2nd case to update r ot l

         So here is the hadful problem.

         At first, I am trying to seperate this case with one conditon:  nums[mid] == nums[r] or..... However that is not general

         Totally, (nums[l] == nums[mid]) && (nums[r] == nums[mid]) {left++, right--} skip相同的元素。知道不同为止。

  Dealing with special case [1,1] or [1] -- determine the case of left and right.

         Idea is from the https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/ -- search in rotated array.

 

public int findMin(int[] nums) {
        int l  =0, r = nums.length-1;
        while(l<r){
            int mid = l+(r-l)/2;
            while((nums[l] == nums[mid]) && (nums[r] == nums[mid]) ) {
                ++l; --r;
                if(l>=nums.length || r<0) break;
            }
            if(l==r) return nums[l];
            else if(l>r) return nums[r+1];
            if(nums[mid] > nums[r]) l = mid+1;
            else r = mid;
        }
        return nums[l];
   }

follow up: find the minimum value index

 

Other thoughts for this problem: if(nums[mid] == nums[r]) h--; /./skip the current high one..

好难得二分查找。。。。

 to be continued... 

 

转载于:https://www.cnblogs.com/stiles/p/154B.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值