581. Shortest Unsorted Continuous Subarray

Solution:

思路:
Time Complexity: O(N) Space Complexity: O(N)

Solution Code:

class Solution {
    public int findUnsortedSubarray(int[] A) {
        int n = A.length;
        int begin = -1, end = -2;
        int min = A[n - 1], max = A[0];
        
        for (int i = 1; i < n; i++) {
          max = Math.max(max, A[i]);
          min = Math.min(min, A[n - 1 - i]);
          if (A[i] < max) end = i;
          if (A[n - 1 - i] > min) begin = n - 1 - i; 
        }
        return end - begin + 1;
    }
}

你可能感兴趣的:(581. Shortest Unsorted Continuous Subarray)