• 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
  • 相关阅读:
    图书馆管理系统

    有理数类的设计
    题目4-多关键字排序(基于自定义比较函数)
    图总结
    树、二叉树、查找算法总结
    数据结构小结
    C语言文件
    第二次博客作业
    第一次博客作业
  • 原文地址:https://www.cnblogs.com/yawenw/p/12716743.html
Copyright © 2020-2023  润新知