欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

581. Shortest Unsorted Continuous Subarray

程序员文章站 2024-02-24 14:47:40
...

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;
    }
}