Skip to content

Latest commit

 

History

History
 
 

581. Shortest Unsorted Continuous Subarray

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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 <= 104
  • -105 <= nums[i] <= 105

 

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

Related Topics:
Array

Solution 1.

// OJ: https://leetcode.com/problems/shortest-unsorted-continuous-subarray/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int findUnsortedSubarray(vector<int>& A) {
        if (A.size() == 1) return 0;
        int N = A.size(), mx = -1e6, left = -1, right = N - 2;
        while (right >= 0 && A[right] <= A[right + 1]) --right;
        if (right < 0) return 0;
        for (int i = 0; i <= right; ++i) {
            mx = max(mx, A[i]);
            while (right + 1 < N && A[right + 1] < mx) ++right;
            if (i - 1 >= 0 && A[i] < A[i - 1]) {
                if (left == -1) left = i;
                while (left - 1 >= 0 && A[left - 1] > A[i]) --left;
            }
        }
        return right - left + 1;
    }
};