连续数组(Java算法每日一题)前缀和+Hashmap

问:
给定一个二进制数组 nums , 找到含有相同数量的 0 和 1 的最长连续子数组,并返回该子数组的长度。
原题链接:https://leetcode.cn/problems/contiguous-array/

例:
输入: nums = [0,1]
输出: 2
说明: [0, 1] 是具有相同数量 0 和 1 的最长连续子数组。

答:

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