581. Shortest Unsorted Continuous Subarray 最短未排序的子数组

来源:互联网 发布:mysql可视化工具下载 编辑:程序博客网 时间:2024/06/15 14:13

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: 5Explanation: 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<=.

题目解释:找出数组中没有正确排序的数组的个数

class Solution {    public int findUnsortedSubarray(int[] nums) {        int n = nums.length;        int max=nums[0];        int begin=-1;        int end=-2;        int 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(max>nums[i])end=i;            if(min<nums[n-1-i])begin=n-1-i;        }        return end-begin+1;    }}

用begin和end分别表示不符合排序要求的首位位置

【O(n)时间复杂度和O(1)空间复杂度】

分别把数组的第一个和最后一个当做最大和最小值

以第一个当做max值来讲,从下一位元素遍历到最后一位元素,取max和元素中的最大值最为更新的max,若max没有被更新,即max>nums[i],说明后一个元素比当前元素小,是不符合题目所说有小到大排序的的,于是把end确定在当前元素位置即i。继续向后遍历直到最后一位,这样可找到小数排在大数后面的情况

把最后一个当做min值得做法,同上

至于begin和end一个被定义成-1,一个被定义成-2,是因为比如说,序列是从小到大排列的,这时候end-begin+1=0,为了满足此公式,作如上定义

以上是我个人想法,可能有偏颇






阅读全文
0 0
原创粉丝点击