581. Shortest Unsorted Continuous Subarray

Sort

T: O(nlogn)

mono stack

T: O(n)

S: O(n)

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int n = nums.length;
        Deque<Integer> stack = new ArrayDeque<>();

        int start = n;
        int end = -1;
        
        // find left boundary
        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && nums[i] < nums[stack.peek()]) {
                
                start = Math.min(start, stack.peek());
                stack.pop();
            }
            stack.push(i);
        }
        
        stack.clear();
        
        // find right boundary
        for (int i = n-1; i >= 0; i--) {
            while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) {
                
                end = Math.max(end, stack.peek());
                stack.pop();
            }
            stack.push(i);
        }
        return Math.max(end - start + 1, 0); // in total acs arrays [1,2,3,4] or [1], result will be negative
    }
}

/*


9
15

*/

python

new

題解可看 labu

Last updated

Was this helpful?