这是问题 “在旋转排序阵列中查找最小值” 的进阶版:
如果允许重复,该怎么办?
这会影响时间复杂度吗?会如何影响和为什么?
假设一个按照升序排列的有序数组从某未知的位置旋转。
(比如 0 1 2 4 5 6 7 可能变成是 4 5 6 7 0 1 2)。
找到其中最小的元素。
数组中可能存在重复的元素。
详见:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/description/

Java实现:

class Solution {
    public int findMin(int[] nums) {
        int n=nums.length;
        int low=0;
        int high=n-1;
        int mid=0;
        while(nums[low]>=nums[high]){
            if(high-low==1){
                mid=high;
                break;
            }
            mid=(low+high)>>1;
            if(nums[low]==nums[mid]&&nums[mid]==nums[high]){
                int mn=nums[low];
                for(int i=low+1;i<=high;++i){
                    if(mn>nums[i]){
                        mn=nums[i];
                    }
                }
                return mn;
            }else if(nums[low]<=nums[mid]){
                low=mid;
            }else if(nums[mid]<=nums[high]){
                high=mid;
            }
        }
        return nums[mid];
    }
}

 python实现:

相关文章:

  • 2022-12-23
  • 2021-08-26
  • 2021-07-12
  • 2021-08-27
  • 2021-08-01
  • 2021-06-04
  • 2022-01-07
猜你喜欢
  • 2021-12-26
  • 2022-12-23
  • 2021-08-21
  • 2022-02-23
  • 2022-02-23
  • 2022-01-21
  • 2021-10-31
相关资源
相似解决方案