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;
    }
}
class Solution {
    public int findUnsortedSubarray(int[] nums) {
        // if there is unsorted subarry, the length of unsorted must be >1,
        // there must be a max, and min value in the unsorted subarray
        boolean isUnsorted= false;
        int unsortedMin = Integer.MAX_VALUE;
        int unsortedMax = Integer.MIN_VALUE;
        
        // looking for the min value of the unsorted subarray, 
        // if ascending is break;
        for(int i=1; i<nums.length; i++){
            if(nums[i]<nums[i-1]){
                isUnsorted = true;
            }
            if (isUnsorted) unsortedMin = Math.min(unsortedMin, nums[i]);
        }
        
        // looking for the max of the unsorted subarray, when descending got broken
        isUnsorted = false;
        for(int i=nums.length-2; i>=0; i--){
           if(nums[i]>nums[i+1]){
               isUnsorted = true;
           }
            if(isUnsorted) unsortedMax=Math.max(unsortedMax, nums[i]);
        }
        
        // looking for the correct position of min and max value
        int l=-1, r=-2;
        for(int i=0; i<nums.length; i++){
            if(nums[i]>unsortedMin){
                l=i;
                break;
            }
        }
        for(int i=nums.length-1; i>=0; i--){
            if(nums[i]<unsortedMax){
                r=i;
                break;
            }
        }
        return r-l+1;
    }
}

Last updated