本文共 1165 字,大约阅读时间需要 3 分钟。
不积跬步无以至千里,不写代码无法进行爱的供养
利用字典cnt,将A,B中各元素(笛卡尔积)的和进行分类计数。 将C,D中各元素(笛卡尔积)和的相反数在cnt中的值进行累加,即为答案。
import collectionsclass 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 defaultdictclass 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
转载地址:http://jbqmi.baihongyu.com/