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     }
  • 相关阅读:
    暑假学习日记2013/7/20
    java二维码之利用谷歌的zxing生成二维码,解析二维码
    数组去重
    MVC VS2012 Code First 数据库迁移教程
    WIN8 MTK驱动不能安装解决办法
    洛谷 P1943 LocalMaxima_NOI导刊2009提高(1)
    BZOJ 1572 USACO 2009 Open 工作安排
    BZOJ 1724 USACO 2006 Nov. 切割木板
    BZOJ 1666 USACO 2006 Oct. 奶牛的数字游戏
    BZOJ 4094 USACO 2013 Dec. Optimal Milking
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7670197.html
Copyright © 2011-2022 走看看