题目:给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。
思路:
既然此题的4个元素分布在4个列表中,结果是相加==0。
那么,感觉无法避免得,要将每一个元素遍历到了。
代码
from typing import List
from collections import OrderedDict
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
res = 0
map = OrderedDict()
for i in range(len(A)):
for j in range(len(B)):
sumAB = A[i]+B[j]
if sumAB in map.keys():
map[sumAB] += 1
else:
map[sumAB] = 1
for i in range(len(C)):
for j in range(len(D)):
sumCD = -(C[i]+D[j])
if sumCD in map.keys():
res += map[sumCD]
return res
if __name__ == '__main__':
res = Solution().fourSumCount([-1,-1],[-1,1],[-1,1],[1,-1])
print(res)