0581. Shortest Unsorted Continuous Subarray (M)

Shortest Unsorted Continuous Subarray (M)

题目

Given an integer array nums, 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.

Return the shortest such subarray and output its length.

Example 1:

Input: nums = [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.

Example 2:

Input: nums = [1,2,3,4]
Output: 0

Example 3:

Input: nums = [1]
Output: 0

Constraints:

  • 1 <= nums.length <= 10^4
  • -10^5 <= nums[i] <= 10^5

Follow up: Can you solve it in O(n) time complexity?


题意

在数组中找到一个最短的子数组,使得当这个子数组排序后,整个数组都是有序的。

思路

因为只需要找一个子数组,我们只要确定这个子数组的左端点和右端点即可,关键是如何判断一个元素是否应该被包含在子数组中。我们可以这样考虑,如果在一个元素的左侧存在着比它大的元素,说明这个元素目前不在最终位置上,需要被包含在子数组中;同样的,如果在一个元素的右侧存在着比它小的元素,这个元素同样需要被包含在子数组中。按照这个思路只需要一次遍历就可以找出子数组的左端点和右端点。


代码实现

Java

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int start = 0, end = -1;		// 这样赋值是为了整体已经有序的情况下可以直接返回
        int leftMax = nums[0], rightMin = nums[nums.length - 1];

        for (int i = 0; i < nums.length; i++) {
            int j = nums.length - 1 - i;

            if (nums[i] < leftMax) end = i;
            leftMax = Math.max(leftMax, nums[i]);

            if (nums[j] > rightMin) start = j;
            rightMin = Math.min(rightMin, nums[j]);
        }

        return end - start + 1;
    }
}
原文地址:https://www.cnblogs.com/mapoos/p/14447746.html