Recursion Solution : Java


  • 0
    A
        public int findUnsortedSubarray(int[] nums) {
            if(nums.length <2)
                return 0;
            int min = findMin(nums);
            int max = findMax(nums);
            if(nums[0] == min && nums[nums.length - 1] == max)
            {
                nums = Arrays.copyOfRange(nums,1,nums.length-1);
                return findUnsortedSubarray(nums);
            }
            else if(nums[0] == min && nums[nums.length -1] != max){
                
                nums = Arrays.copyOfRange(nums,1,nums.length);
                return findUnsortedSubarray(nums);
                
            }
            else if(nums[0]!= min && nums[nums.length -1] == max){
                nums = Arrays.copyOfRange(nums,0,nums.length-1);
                return findUnsortedSubarray(nums);
            }
            return nums.length;
            
        }
    
        public int findMin(int[] nums){
            int min = nums[0];
            for (int i=1; i< nums.length; i++){
                if(nums[i]<min)
                    min = nums[i];
            }
            return min;
        }
        public int findMax(int[] nums){
            int max = nums[0];
            for (int i=1; i< nums.length; i++){
                if(nums[i]>max)
                    max = nums[i];
            }
            return max;
        }
    }
    It has very bad runtime, but I felt like I can use some recommendations.
    Thanks for reading :)

Log in to reply
 

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