Cloning the array space compexity O(n)


  • 0
    D

    I make a clone of the array and compare the two arrays and when the index varies then i assign it to the max and min and max will change only when the min change as it is determine by the flag.

    class Solution {
        public int findUnsortedSubarray(int[] nums) {
            int min = 0;
            int max = 0;
            boolean flag = false;
            int[] snums = nums.clone();
            Arrays.sort(snums);
            for(int i = 0; i < nums.length; ++i) {
                if(nums[i] != snums[i]) {
                    if(flag == false) {
                        min = i;
                        flag = true;
                    }
                    else {
                        max = i;
                    }
                }       
            }
            if(flag == false) {
                return 0;
            }
            else {
                return max - min + 1;
            }
        }
    }
    

Log in to reply
 

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