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     }
  • 相关阅读:
    50个提高PHP程序运行效率的方法
    虚拟主机FTP上传文件为什么要用二进制上传
    Status Bar 总结
    TableView 总结
    阿里Java开发手册(泰山版)个人记录
    下载excel模板
    微信公众号-发送模板消息
    ffmpeg获取视频时长
    微信公众号授权
    根据word模板生成word、转换成pdf、打成war包
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7670197.html
Copyright © 2011-2022 走看看