Java. Simple. Beats 99%


  • 0
    S

    I use an array rather than a HashMap.

        
        public int findMaxLength(int[] nums) {
                    
            int ones = 0;
            int zeroes = 0;
            
            int tr = 0;
            
            int[] past = new int[nums.length*2+1];
            
            Arrays.fill(past, -1);
            
            for(int i=0;i<nums.length;i++){
                
                if(nums[i] == 1) ones++;
                
                if(nums[i] == 0) zeroes++;
                
                int diff = nums.length+ones - zeroes;
                
                if(ones-zeroes==0){
                    
                    tr = Math.max(tr, i+1);
                    
                    continue;
                    
                }
                
                if(past[diff] > -1) tr = Math.max(tr, i-past[diff]);
                   
                if(past[diff] == -1) past[diff] = i;
                
            }
            
            return tr;
            
        }
        
    }

Log in to reply
 

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