其他分享
首页 > 其他分享> > [LeetCode] 581. Shortest Unsorted Continuous Subarray

[LeetCode] 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 <=.

最短无序连续子数组。题意是给一个无序的整数数组,你需要找一个子数组,并对这个子数组排序,使得子数组排序后再放回原数组能把整个数组变成有序的。请返回一个最短的子数组的长度。

思路是双指针,具体做法是这样的。既然是尽量翻转一个较短的子数组,那么如果用两个指针往中间逼近的时候,靠外的数字较小,靠中间的数组较大,比如左半边一直是nums[l] < nums[l + 1],右半边一直是nums[r] > nums[r + 1]。那么两个指针都会逼近;一旦不满足这个条件的时候,就说明中间有一部分开始是乱序的了,此时结算一下左边指针和右边指针的距离即可。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int findUnsortedSubarray(int[] nums) {
 3         int len = nums.length;
 4         int max = nums[0];
 5         int min = nums[len - 1];
 6         int l = 0;
 7         int r = -1;
 8         for (int i = 0; i < len; i++) {
 9             if (nums[i] < max) {
10                 r = i;
11             } else {
12                 max = nums[i];
13             }
14             if (nums[len - i - 1] > min) {
15                 l = len - i - 1;
16             } else {
17                 min = nums[len - i - 1];
18             }
19         }
20         return r - l + 1;
21     }
22 }

 

JavaScript实现

 1 /**
 2  * @param {number[]} nums
 3  * @return {number}
 4  */
 5 var findUnsortedSubarray = function (nums) {
 6     let len = nums.length;
 7     let max = nums[0];
 8     let min = nums[len - 1];
 9     let l = 0;
10     let r = -1;
11     for (let i = 0; i < nums.length; i++) {
12         if (nums[i] < max) {
13             r = i;
14         } else {
15             max = nums[i];
16         }
17         if (nums[len - 1 - i] > min) {
18             l = len - 1 - i;
19         } else {
20             min = nums[len - 1 - i];
21         }
22     }
23     return r - l + 1;
24 };

 

LeetCode 题目总结

标签:数组,nums,int,max,Continuous,len,let,Unsorted,581
来源: https://www.cnblogs.com/cnoodle/p/13694562.html