30-Day Leetcoding Challenge Day13

本题的关键是用一个计数器count=0,遇到0减1,遇到1加1.这让我联想到了()匹配。也可以用计数器的方式判断

如果用暴力法超时,这时用了map{count,index}这样的数据结构。这里又和twoSum这道题相似。

其实这道题的解法 是集成了 括号匹配两数之和 的方法。

JAVA

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

Python3

class Solution:
    def findMaxLength(self, nums: List[int]) -> int:
        res = 0
        count = 0
        d = dict()
        d[0] = -1
        for i in range(len(nums)):
            count += -1 if nums[i]==0 else nums[i]==1
            if count in d:
                res = max(res, i-d[count])
            else:
                d[count] = i
        return res
原文地址:https://www.cnblogs.com/yawenw/p/12716743.html