Easy Java Solution, HashMap


  • 1
    D

    public class Solution {
    public int findMaxLength(int[] nums) {
    if(nums == null || nums.length == 0) {
    return 0;
    }

        Map<Integer, List<Integer>> map = new HashMap<>();
        map.put(0, new ArrayList<>());
        map.get(0).add(0);
        int sum = 0;
        
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] == 0) {
                sum--;
            } else {
                sum++;
            }
            
            if(!map.containsKey(sum)) {
                map.put(sum, new ArrayList<>());
            }
            
            map.get(sum).add(i + 1);
        }
        
        int maxLength = 0;
        for(List<Integer> val : map.values()) {
            maxLength = Math.max(maxLength, val.get(val.size() - 1) - val.get(0));
        }
        
        return maxLength;
    }
    

    }


Log in to reply
 

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