zoukankan      html  css  js  c++  java
  • 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.

    Note:

    1. Then length of the input array is in range [1, 10,000].
    2. The input array may contain duplicates, so ascending order here means <=.

    题目含义:这道题是要找出最短的子数组,将此子数组按照升序排列以后,整个数组就符合升序排列了。

    思路一:先用一个数组temp保存nums,然后对temp排序,然后用两个变量start和end去找两个数组出现不同之处的第一个位置和最后一个位置,最后返回end-start+1就是要找的数组长度

     1     public int findUnsortedSubarray(int[] nums) {
     2         int n = nums.length;
     3         int[] temp = new int[n];
     4         Arrays.copyOfRange(nums,0,nums.length-1);
     5         Arrays.sort(temp);
     6         int start = 0;
     7         while (start < n  && nums[start] == temp[start]) start++;
     8         int end = n - 1;
     9         while (end > start  && nums[end] == temp[end]) end--;
    10         return end - start + 1;
    11     }

    方法二:

    从前开始往后遍历,找到开始位置,从后往前遍历,找到结束位置,最后返回区间。

    以  0,1,2,5,4,3,6,7为例,最终end=5,begin=3

     1     public int findUnsortedSubarray(int[] nums) {
     2         int n = nums.length, beg = -1, end = -2, min = nums[n-1], max = nums[0];
     3         for (int i=1;i<n;i++) {
     4             max = Math.max(max, nums[i]);
     5             min = Math.min(min, nums[n-1-i]);
     6             if (nums[i] < max) end = i;
     7             if (nums[n-1-i] > min) beg = n-1-i;
     8         }
     9         return end - beg + 1;
    10     }
  • 相关阅读:
    module 和 component 的区别
    API、SDK、DLL有什么用?
    app基本控件
    PaaS是什么?
    js回调函数(callback)(转载)
    多语言 SEO
    axure rp 8.0
    整天看用户埋点数据,知道数据是咋来的吗?
    发现恶意ip大量访问 可使用命令进行封禁
    阿里云服务器迁移更改IP,导致网站挂掉
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7670197.html
Copyright © 2011-2022 走看看