LeetCode #454 2018-07-28

454. 4Sum II

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:
2
Explanation:
The two tuples are:

  1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
  2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

https://leetcode.com/problems/4sum-ii/description/

这道题巧妙的利用的python种的Counter类,总的时间复杂度为O(n2), 空间复杂度是O(n2)
代码如下:

class Solution:
    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])
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 专业考题类型管理运行工作负责人一般作业考题内容选项A选项B选项C选项D选项E选项F正确答案 变电单选GYSZ本规程...
    小白兔去钓鱼阅读 13,029评论 0 13
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,172评论 0 10
  • 在C语言中,五种基本数据类型存储空间长度的排列顺序是: A)char B)char=int<=float C)ch...
    夏天再来阅读 8,916评论 0 2
  • 《爱丽丝镜中世界奇遇记》里有一个片段是这样的: 爱丽丝和红王后一起跑步,跑到最后都快跑到累死了,发现还在原来的地方...
    兰安晨Rita阅读 4,155评论 0 0
  • 用心经营 生活的一切都需要用心经营。 用心经营了,婚姻就还是甜蜜的爱情; 用心经营了,友情只会越来越深厚;用心经营...
    迎lvying阅读 2,844评论 0 0

友情链接更多精彩内容