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;
        }
    }
  • 相关阅读:
    UVA10765图论+点-双连通分量性质应用
    LA4287图论+ 有向图SCC+缩点
    LA5135图论+ 割点性质运用
    LA2572计算几何+离散化+面的覆盖
    LA2402暴力枚举+计算几何+四边形面积
    UVA10566计算几何+相似三角形比例函数+二分范围的辨析
    UVA11300计算几何:正n边形内的最长的线
    UVA11524平面几何+二分法+海伦公式
    LA4986三分法求出凹性函数最小值+计算几何
    胜利大逃亡--hdu --1253(bfs)
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/14450234.html
Copyright © 2011-2022 走看看