【leetcode】454. 4Sum II【M】

来源:互联网 发布:中国跳水最厉害的知乎 编辑:程序博客网 时间:2024/06/01 19:44

Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

Example:

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

Subscribe to see which companies asked this question


最开始想的是固定前三个数,然后看第四个数满足条件否

显然,超时了

而且,这时候才意识到,list 判断in的时候,是o(n)的

然后就想,A+B放一起,也就500*500个,然后再去判断CD的

嗯。。。就可以了


class Solution(object):    def fourSumCount(self, A, B, C, D):        res2 = {}        res = 0        for i in C:            for j in D:                res2[i+j] = res2.get(i+j,0) + 1        for i in A:            for j in B:                res += res2.get(-i-j,0)        return res


0 0
原创粉丝点击