9-line AC Java with HashMap


  • 0
    A
    public int findMaxLength(int[] nums) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        int res = 0, cnt = 0; // cnt records how many more '1' than '0'        
        for(int i=0; i<nums.length; i++){
            cnt = nums[i]==1 ? cnt+1 : cnt-1;
            if(cnt == 0) res = i+1; //Math.max(res, i+1);
            else if(map.containsKey(cnt)) res = Math.max(res, i-map.get(cnt));
            else map.put(cnt, i);
        }
        return res;        
    }

Log in to reply
 

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