運(yùn)用二分法的思想,四個(gè)數(shù)組A,B,C,D.
A+B進(jìn)行統(tǒng)計(jì),-C-D進(jìn)行統(tǒng)計(jì).這樣就將問(wèn)題化簡(jiǎn).
調(diào)用標(biāo)準(zhǔn)庫(kù)collections
的Counter
方法,可以非常Pythonic.
也可以自己用字典實(shí)現(xiàn),只是代碼長(zhǎng)一點(diǎn).
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
"""
ab = collections.Counter(a+b for a in A for b in B)
return sum(ab[-c-d] for c in C for d in D)