Note: 1. Remember to intial (0, -1) since this kind of problems need a starting point.

class Solution {
    public int findMaxLength(int[] nums) {
        if (nums.length < 2) {
            return 0;
        } 
        
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                nums[i] = -1;
            }
        }
        
        Map<Integer, Integer> sumMap = new HashMap<>();
        sumMap.put(0, -1);
        int sum = 0;
        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (!sumMap.containsKey(sum)) {
                sumMap.put(sum, i);
            } else {
                result = Math.max(result, i - sumMap.get(sum));
            }
        }
        return result;
    }
}

 

posted on 2017-09-03 16:02  keepshuatishuati  阅读(81)  评论(0编辑  收藏  举报