Leetcode 581.最短无序连续子数组

最短无序连续子数组

给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。

你找到的子数组应是最短的,请输出它的长度。

示例 1:

输入: [2, 6, 4, 8, 10, 9, 15]

输出: 5

解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。

说明 :

  1. 输入的数组长度范围在 [1, 10,000]。
  2. 输入的数组可能包含重复元素 ,所以升序的意思是<=。

  题目给了我们一个nums array, 让我们找出一个最短的无序连续子数组,当我们把这个子数组排序之后,整个array就已经是排序的了。

  要找到这个子数组的范围,先要了解这个范围的beg 和 end 是如何定义的。

  来看这个例子:1 3 5 7 2 4 5 6

  a. 当我们找到第一个违反ascending 排序的数字 2的时候,我们不能是仅仅把beg 标记为2的前面一个数字7,而是要一直往前,找到一个合适的位置,找到在最前面位置的比2大的数字,这里是3。

  b. 同样的,为了找end, 那么我们要从7的后面开始找,一直找到一个最后面位置的比7小的数字,这里是6。

  这样的话,范围就是3到6 是我们要找的子数组。把3到6排序完了之后,整个array 就已经是排序的了。

   

  这里我们可以发现,2是min, 7是max,所以我们可以分两个方向来分别寻找beg 和end。

  从右到左(绿色),维护更新min 和 beg;

  从左到右(红色),维护更新max 和 end。

 1 class Solution
 2 {
 3     public int findUnsortedSubarray(int[] nums)
 4     {
 5         int n = nums.length;
 6         int beg = -1;
 7         int end = -2; // end is -2 is because it works if the array is already in ascending order
 8         int min = nums[n-1]; // from right to left
 9         int max = nums[0];      // from left to right
10 
11         for(int i=0; i<n; i++)
12         {
13             max = Math.max(max, nums[i]);
14             min = Math.min(min, nums[n-1-i]);
15 
16             if(nums[i] < max)
17                 end = i;
18             if(nums[n-1-i] > min)
19                 beg = n-1-i;
20         }
21 
22         return end - beg + 1; // if array is already in ascending order, -2 - (-1) + 1 = 0
23     }
24 }
原文地址:https://www.cnblogs.com/kexinxin/p/10381393.html