博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode454. 4Sum II(思路及python解法)
阅读量:2242 次
发布时间:2019-05-09

本文共 1236 字,大约阅读时间需要 4 分钟。

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

和之前的3sum有所不同,这个题的每个数在不同数组里,所以直接用4个for循环即可。

把ABCD分成两组计算,计算速度会快一些。

class Solution:    def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:        dic = {}        for a in A:            for b in B :                dic[a+b]=dic.get(a+b,0)+1        count = 0                 for c in C :            for d in D :                if -c-d in dic:                    count += dic[-c-d]        return count

用collections可以写的更简单一些。

class Solution:    def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:        sumab=collections.Counter(a+b for a in A for b in B)        return sum(sumab[-c-d] for c in C for d in D)

 

转载地址:http://cjrbb.baihongyu.com/

你可能感兴趣的文章
oracle 的 SDO_GEOMETRY
查看>>
往oracle中插入geometry的两种方式
查看>>
Oracle Spatial中的Operator操作子 详细说明
查看>>
Oracle Spatial中SDO_Geometry详细说明
查看>>
oracle 聚合函数 LISTAGG ,将多行结果合并成一行
查看>>
Oracle列转行函数 Listagg() 语法详解及应用实例
查看>>
LISTAGG函数的用法
查看>>
Oracle Spatial操作geometry方法
查看>>
IDEA类和方法注释模板设置(非常详细)
查看>>
Java程序初始化的顺序
查看>>
Dubbo和Spring结合配置文件内容解析为bean的过程
查看>>
fastJson注解@JSONField使用的一个实例
查看>>
fastjson的@JSONField注解的一点问题
查看>>
fastjson使用(三) -- 序列化
查看>>
浅谈使用单元素的枚举类型实现单例模式
查看>>
Java 利用枚举实现单例模式
查看>>
Java 动态代理作用是什么?
查看>>
Java动态代理机制详解(JDK 和CGLIB,Javassist,ASM) (清晰,浅显)
查看>>
三种线程安全的单例模式
查看>>
Spring AOP 和 动态代理技术
查看>>