problem description:
there is four number list named A,B,C,D; now you should out put the num of tuples which statisfy A[i] +B[j]+C[k]+D[l] =0
i.e:
Input:A = [ 1, 2]B = [-2,-1]C = [-1, 2]D = [ 0, 2]Output:2Explanation:The two tuples are:1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 02. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0 解法:主要方法采用的是哈希表。将A和B列表中的每个值都进行两两相加,将得出的值作为哈希表的索引然后将哈希表该索引下的值加一。然后将C和D中的每个值两两相加,将所得出的值的相反数作为哈希表的索引,即可 得知相应的值有几种解法,然后进行累加。 python 实现方式:
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 """ dicts = {} for i in A: for j in B: sums = i+j if sums not in dicts: dicts[sums] = 1 else: dicts[sums] += 1 out = 0 for k in C: for l in D: sums =-(k + l) if sums in dicts: out += dicts[sums] return out
以上的方法虽有不错,但是还不是最精炼的python代码:
最精炼的python代码,用到了counter模块下的collection函数。它能够统计出相同数值的个数,本质上还是个哈希表
def fourSumCount(self, A, B, C, D): 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)
以上的第一个代码是个人想法,第二个精炼的代码参考自leetcode上stefanporchmann的代码