zoukankan      html  css  js  c++  java
  • 581. Shortest Unsorted Continuous Subarray

    Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.

    Return the shortest such subarray and output its length.

    Example 1:

    Input: nums = [2,6,4,8,10,9,15]
    Output: 5
    Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
    

    Example 2:

    Input: nums = [1,2,3,4]
    Output: 0
    

    Example 3:

    Input: nums = [1]
    Output: 0
    

    Constraints:

    • 1 <= nums.length <= 104
    • -105 <= nums[i] <= 105
    class Solution {
        public int findUnsortedSubarray(int[] nums) {
            int l = 0, r = nums.length - 1, n = nums.length;
            
            while((l + 1) < n && nums[l] < nums[l + 1]) l++;
            while((r - 1) >= 0 && nums[r] >= nums[r - 1]) r--;
            
            return r - l > 0 ? r - l + 1 : 0;
        }
    }

    首先想到从左右两边开始看到哪一位违反了rule,然后 r - l + 1.

    但是不能这么简单的做判断,因为有【1,2,3,3,3】或者【1,3,2,2,2】这种情况。前者和后者对于终止条件判断是不一样的,前者不需要r前移,而后者需要。所以要考虑别的方法,。

    思考过程:从左往右如果当前数小于之前最大的数,说明起码从这里开始就要sort了,然后设这里为右终点r,因为我们还要往后比较,r越来越大

    相对的,从右往左如果当前数大于之前最小的数,说明也要至少从这里开始sort。设这里为左终点l,l往前越来越小

    class Solution {
        public int findUnsortedSubarray(int[] nums) {
            int l = -1, r = -1, n = nums.length;
            int curmax = Integer.MIN_VALUE;
            int curmin = Integer.MAX_VALUE;
            for(int i = 0; i < n; i++) {
                curmax = Math.max(curmax, nums[i]);
                curmin = Math.min(curmin, nums[n - i - 1]);
                
                if(nums[i] < curmax) r = i;
                if(nums[n - i - 1] > curmin) l = n - 1 - i;
            }
            
            return l == -1 ? 0 : r - l + 1;
        }
    }
  • 相关阅读:
    VisionPro 各控件的C#中类库 CogAcqFifoTool(2)
    VisionPro 各控件的C#中类库 CogAcqFifoTool(1)
    C# new的三种用法
    C# as用法
    C# 基类之Environment类
    C#开发的软件在Windows7中出现对路径的访问被拒绝异常
    IDEA创建springboot项目【mas-service】
    .Net Core-ObjectPool
    中介者模式的实现-MediatR
    .NET Core分布式事件总线、分布式事务解决方案:CAP
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/14450234.html
Copyright © 2011-2022 走看看