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

    Given an integer array, 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, too.

    You need to find the shortest such subarray and output its length.

    Example 1:

    Input: [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.



    class Solution {
        public int findUnsortedSubarray(int[] nums) {
            int n=nums.length,end=-2,start=-1,max=nums[0],min=nums[n-1];
            for(int i=1;i<n;i++){
                max=Math.max(max,nums[i]);
                min=Math.min(min,nums[n-1-i]);
                if(nums[i]<max)end=i;
                if(nums[n-1-i]>min)start=n-1-i;
            }
            return end-start+1;
        }
    }
    class Solution {
        public int findUnsortedSubarray(int[] nums) {
            int[] nn=nums.clone();
            Arrays.sort(nn);
            int l=nums.length,r=0;
            for(int i=0;i<nums.length;i++){
                if(nums[i]!=nn[i]){
                    l=Math.min(l,i);
                    r=Math.max(r,i);
                }
            }
            return r-l<0?0:r-l+1;
        }
    }
  • 相关阅读:
    GitLab备份与恢复
    内网穿透frp
    Python Day21-22(Django进阶)
    Python Day19-20(Django基础)
    Python Day18(Django初识)
    Python Day17(jQuery)
    Python day16(JavaScript)
    Python Day15(CSS)
    Unity组件
    关于游戏
  • 原文地址:https://www.cnblogs.com/albert67/p/10434312.html
Copyright © 2011-2022 走看看