175.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.
说明:您需要按升序对[6,4,8,10,9]进行排序,以使整个数组按升序排序。

Note:

  1. Then length of the input array is in range [1, 10,000].然后输入数组的长度在[1,100]范围内。
  2. The input array may contain duplicates, so ascending order here means <=.输入数组可能包含重复项,因此这里的升序表示<=。

解答:

 时间复杂度O(n),空间复杂度O(1)

 1 class Solution {
 2     public int findUnsortedSubarray(int[] nums) {
 3         int start=-1,end=-2,n=nums.length,max=nums[0],min=nums[n-1];
 4         
 5         for(int i=1;i<n;i++){
 6             max=Math.max(max,nums[i]);
 7             min=Math.min(min,nums[n-1-i]);
 8             if(max>nums[i]) end=i;
 9             if(nums[n-i-1]>min) start=n-1-i;
10         }
11         
12         return end-start+1;
13     }
14 }

详解:

令start=-1,end=-2,这样end-start+1=0,即需要排序的子序列长度为0。

排好序的数组一定是前项<后项,end从前往后遍历,start从后往前遍历。

max为从前往后遍历时遇到的最大值,min为从后往前遍历时遇到的最小值。

如果max>当前项nums[i],说明此项大小异常,标记。

如果当前项nums[n-1-i]>min,说明此项大小异常,标记。

[2,6,4,8,10,15]

i=1,end=-2,start=-1,max=6,min=9

i=2,end=2, start=4, max=6,min=9

i=3,end=2, start=4, max=8,min=8

i=4,end=2,start=4,max=10,min=4

i=5,end=5,start=1,max=10,min=4

i=6,end=5,start=1,max=15,min=2

猜你喜欢

转载自www.cnblogs.com/chanaichao/p/9667705.html