Java O(n) solution, using sum + HashMap


  • 0
    M

    Idea:

    1. replace 0 with -1. Then if sum of subarray is 0, the subarray contains equal number of 0 and 1.

    2. Then if cur_sum==first_sum, the sum between index(cur_sum) and index(first_sum) = 0.

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

Log in to reply
 

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