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;
        }
    }
  • 相关阅读:
    debian源
    python查找字符串所有子串
    python格式化输出
    Nmap扫描常用参数
    生日攻击
    python 逻辑运算符问题
    python装饰器中的计时器thd.strat用法
    One-hot encoding 独热编码
    协同过滤算法 teamCF
    bootstrap boosting bagging辨析
  • 原文地址:https://www.cnblogs.com/albert67/p/10434312.html
Copyright © 2011-2022 走看看