Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.

You need to find the shortest such subarray and output its length.

Example 1:

Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.



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

 

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int[] nn=nums.clone();
        Arrays.sort(nn);
        int l=nums.length,r=0;
        for(int i=0;i<nums.length;i++){
            if(nums[i]!=nn[i]){
                l=Math.min(l,i);
                r=Math.max(r,i);
            }
        }
        return r-l<0?0:r-l+1;
    }
}