Leetcode Hash Table知识点总结

136 篇文章 0 订阅
33 篇文章 0 订阅

不积跬步无以至千里,不写代码无法进行爱的供养


  • 454. 4Sum II:求满足A[i]+B[j]+C[k]+D[l] = 0的 (i,j,k,l)个数,Medium

http://bookshadow.com/weblog/2016/11/13/leetcode-4sum-ii/
利用字典cnt,将A,B中各元素(笛卡尔积)的和进行分类计数。
将C,D中各元素(笛卡尔积)和的相反数在cnt中的值进行累加,即为答案。

import collections
class Solution(object):
    def fourSumCount(self, A, B, C, D):
        """
        :type A: List[int]
        :type B: List[int]
        :type C: List[int]
        :type D: List[int]
        :rtype: int
        """
        ans = 0
        cnt = collections.defaultdict(int)
        for x in A:
            for y in B:
                cnt[x+y]+=1
        for x in C:
            for y in D:
                ans += cnt[-(x+y)]
        return ans
from collections import defaultdict
class Solution(object):
    def subdomainVisits(self, cpdomains):
        """
        :type cpdomains: List[str]
        :rtype: List[str]
        """
        maps = defaultdict(int)
        for cpdomain in cpdomains:
            cpdomain = cpdomain.split()
            count = int(cpdomain[0])
            strs = cpdomain[1].split('.')
            for i in range(len(strs)):
                s = '.'.join(strs[i:])
                maps[s]+=count
        ret = []
        for a in maps:
            ret += [str(maps[a])+' '+a]
        return ret
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值