581. Shortest Unsorted Continuous Subarray!

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int len = nums.length;
        int l = -1, r = -2;
        // set the first ele as the max, 
        // and looking for larger element with ascending order.
        // when there is element smaller than the max, 
        // we know the ascending order is broken.
        // continue the iteration and track the max, when there is no element smaller than max, we get the right boundary of the unsoted subarray
        int unsortedMax = nums[0];
        // set the last element as the min,
        // and looing for smaller element with descending order.
        // when there is an element larger then the min, 
        // we know the descending order is broken.
        // continue the iteration and check the min, when there is no element larger then the min, we get the left boundary of the unsorted subarray
        int unsortedMin = nums[nums.length-1];
        
        for (int i=1; i<len; i++){
            unsortedMax = Math.max(nums[i], unsortedMax);
            if (unsortedMax>nums[i]) r=i;
            
            unsortedMin = Math.min(nums[len-i-1], unsortedMin);
            if (unsortedMin<nums[len-i-1]) l=len-i-1;
        }
        return r-l+1;
    }
}

Last updated

Was this helpful?