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;
        }
    }
  • 相关阅读:
    Filter过滤器
    jsp-JSTL表达式
    jsp-EL表达式
    JSP概述
    servlet编码问题
    微信开放平台-踩坑1
    Supervisor的安装以及使用
    laravel-mix的安装
    Laravel框架中打印sql
    Laravel 5.7 使用 PHP artisan migrate 的问题
  • 原文地址:https://www.cnblogs.com/albert67/p/10434312.html
Copyright © 2011-2022 走看看