My java unsorting solution


  • 0
    C
    public class Solution {
    public int findUnsortedSubarray(int[] nums) {
        //if it is null, return null
        if(nums == null || nums.length == 1)
            return 0;
        //if it only has two elements, compare once.
        if(nums.length == 2 && nums[0]>nums[1])
            return 2;
        //for those arrays larger than 3
        
        //first & last initial should be same
        int first = 0;
        int last  = nums.length-1;
        
        int count_min = 0;
        int count_max = 0;
        
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        
        //how to deal with duplicates??
        
        for(int i=0;i<nums.length-1;i++)
        {
            if(nums[i] > nums[i+1])
            {
                first = i;
                break;
            }
            
        }
        
        for(int j=nums.length-1;j>0;j--)
        {
            if(nums[j] < nums[j-1])
            {
                last = j;
                break;
            }
        }
        
        for(int i=first;i<=last;i++)
        {
            max = max>nums[i]?max:nums[i];
            min = min<nums[i]?min:nums[i];
        }
        
        for(int i=0;i<first;i++)
        {
            if(nums[i] > min)
            {
                count_min++;
            }
            
        }
        
        for(int i=nums.length-1;i>last;i--)
        {
            if(nums[i] < max)
            {
                count_max++;
            }
        }
        
        System.out.print(last+" "+first+" "+count_min+" "+count_max);
        if(first == 0 && last == nums.length-1)
        {
            
            for(int i=0;i<nums.length-1;i++)
            {
                if(nums[i] >nums[i+1])
                {
                    return nums.length;
                }
            }
            
            return 0;
        }
        return last-first+1+count_min+count_max;   
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.