454. 4Sum II

Add to List

Description Submission Solutions

  • Total Accepted: 8398
  • Total Submissions: 18801
  • Difficulty: Medium
  • Contributors: Samuri

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

Subscribe to see which companies asked this question.

【题目分析】

给定四个长度相同的数组,在每个数组中取一个数字,在所有的组合中和为零的组合有多少个?

【思路】

把四个数组分为两组,每组包含两个数组。把其中一组中的任意两个值和存入hashmap中,然后在hashmap查找另外两个数组的值的组合。这其实是相当于转化为了一个two sum问题。

【java代码】

 public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
Map<Integer, Integer> map = new HashMap<>(); for(int i=0; i<C.length; i++) {
for(int j=0; j<D.length; j++) {
int sum = C[i] + D[j];
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
} int res=0;
for(int i=0; i<A.length; i++) {
for(int j=0; j<B.length; j++) {
res += map.getOrDefault(-1 * (A[i]+B[j]), 0);
}
} return res;
}

代码中的map.getOrDefault(sum, 0)相比先在map中查找再取数的操作是比较高效的。

最新文章

  1. 一个语句创建Oracle所有表的序列
  2. Pyqt5 获取命令行参数sys.argv
  3. Struts2的值栈和对象栈
  4. Group的操作
  5. 性能优化-查询最耗CPU的SESSION与SQL
  6. Jquery datatables 重载数据方法
  7. (转)Linux 文件系统:procfs, sysfs, debugfs 用法简介
  8. 利用CryptoStream进行加密解密
  9. 折腾Python中的Tkinter
  10. 【MySQL】MySQL零碎积累
  11. 前端开发 JavaScript 规范文档
  12. 错误ERROR datanode.DataNode (DataXceiver.java:run(278)) - hadoop07:50010DataXceiver error processing unknown operation src:127.0.0.136479 dst:127.0.0.150010
  13. github 生成配置ssh 秘钥方法详解
  14. Simplest Python K-Way Merging Sort|最简单的Python k路归并排序
  15. Codeforces Beta Round #19C. Deletion of Repeats
  16. css兼容问题(一)
  17. CF446 (Div. 1)简单题解
  18. TCP的状态转移
  19. SSM框架搭建总结(2)
  20. ASP.NET 5 RC 1:UrlRouting 设置(不包含MVC6的UrlRouting设置)

热门文章

  1. BC#29A:GTY&#39;s math problem(math) B:GTY&#39;s birthday gift(矩阵快速幂)
  2. 模块讲解----json与pickle模块的区别
  3. 闪回事务(Flashback Transaction)
  4. AngularJS 笔记系列(四)控制器和表达式
  5. WEB前端研发工程师编程能力成长之路(2)
  6. C# 导出 Excel 的各种方法总结
  7. 斐讯面试记录—三线程交替打印ABC
  8. ubuntu apt-get 安装 lnmp
  9. LRU算法---缓存淘汰算法
  10. SpringSource Tool Suite (STS)无法启动问题