zoukankan      html  css  js  c++  java
  • LeetCode | Find Minimum in Rotated Sorted Array II

    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.

    // [小][大] ->(rotate)-> [大][小],只有在pivot处才会有逆序
    public class Solution {
        public int findMin(int[] nums) {
            
            int result = Integer.MAX_VALUE;
            int left = 0;
            int right = nums.length - 1;
            
            while(left <= right){
                int middle = (left + right) / 2;
                
                if(nums[middle] < nums[right]){          //m-r段有序
                    if(nums[middle] < result){
                        result = nums[middle];
                    }
                    right = middle - 1;
                }else if(nums[middle] > nums[right]){    //l-m段有序
                    if(nums[left] < result){
                        result = nums[left];
                    }
                    left = middle + 1;
                }else{                                   //不能判断,移动边缘
                    if(nums[right] < result){
                        result = nums[right];
                    }
                    right--;
                }
            }
            
            return result;
        }
    }



  • 相关阅读:
    描述网络的优点与缺点
    外键之表格三种关系
    Mysql完整性约束
    Mysql数据类型
    mysql的基本语句
    Mysql的基本安装
    type与object的关系
    反射
    面向对象内置方法(进阶)
    Python 的五种io模型理解
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444425.html
Copyright © 2011-2022 走看看