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;
        }
    }
  • 相关阅读:
    Linux文件结构
    磁盘分区
    BASH简介
    磁盘的基本概念
    Linux文件操作
    创建文件系统
    文件系统挂载
    一些常用命令
    asp.net创建PPT
    asp.net创建、删除、移动文件夹 文件
  • 原文地址:https://www.cnblogs.com/albert67/p/10434312.html
Copyright © 2011-2022 走看看