【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
- 【leetcode】454. 4Sum II【M】
- LeetCode 454. 4Sum II
- Leetcode-454. 4Sum II
- LeetCode 454. 4Sum II
- Leetcode-454. 4Sum II
- 【LeetCode】 454. 4Sum II
- [leetcode]454. 4Sum II
- 【Leetcode】454. 4Sum II
- Leetcode 454. 4Sum II
- LeetCode 454. 4Sum II
- [LeetCode] 454. 4Sum II
- leetcode 454. 4Sum II
- leetcode 454. 4Sum II
- LeetCode 454. 4Sum II
- Leetcode: 454. 4Sum II
- leetcode 454. 4Sum II
- leetcode 454. 4Sum II
- [leetcode] 454. 4Sum II
- centos7安装nfs服务
- JVM基础(7)——jdk常用内置工具
- Linux+db2+was部署问题总结
- 【iOS开发】在程序被送入后台时,开启一个长期任务(voip)。
- VC++ 出现Debug Assertion Failed!
- 【leetcode】454. 4Sum II【M】
- augmented reality(AR)入门实例
- JavaScript——split函数的应用
- linux内核目录树
- vba获取单元的背景颜色
- Android:Looper, Handler, And HandlerThread(二)
- 关于对话框和popupwindow的设置指定大小和位置的小结
- kafka生产者示例(kafka-python producer example)
- 求100以内的勾股数