LeetCode 525. Contiguous Array

Problem Description:

Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.

题解:

这个题很容易想到复杂度为O(n^2)的暴力方法。看了提示HashMap后想了大概半个小时想到了O(n)的解法。

我的想法是用HasmMap<Integer, Integer> map , Key是从头到index的和,value是早出现该sum的index。不同的是遇到1sum+=1,而遇到0时sum-=1.

这样到出现相同的key时,更新res。

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

 

posted @ 2019-03-29 17:00  起点菜鸟  阅读(119)  评论(0)    收藏  举报