Java one pass solution, HashMap


  • 0
        public int findMaxLength(int[] nums) {
            if (nums == null || nums.length < 2) {
                return 0;
            } 
            int maxLen = 0;
            int delta = 0;
            Map<Integer, Integer> map = new HashMap<>();
            map.put(0, -1);
            for (int i = 0; i < nums.length; i++) {
                delta += (nums[i] == 1 ? 1 : -1);
                if (map.containsKey(delta)) {
                    maxLen = Math.max(maxLen, i - map.get(delta));
                } else {
                    map.put(delta, i);
                }
            }
            return maxLen;
        }
    

Log in to reply
 

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