LeetCode 454. 4Sum II
2024-08-25 22:15:56
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中查找再取数的操作是比较高效的。
最新文章
- 一个语句创建Oracle所有表的序列
- Pyqt5 获取命令行参数sys.argv
- Struts2的值栈和对象栈
- Group的操作
- 性能优化-查询最耗CPU的SESSION与SQL
- Jquery datatables 重载数据方法
- (转)Linux 文件系统:procfs, sysfs, debugfs 用法简介
- 利用CryptoStream进行加密解密
- 折腾Python中的Tkinter
- 【MySQL】MySQL零碎积累
- 前端开发 JavaScript 规范文档
- 错误ERROR datanode.DataNode (DataXceiver.java:run(278)) - hadoop07:50010DataXceiver error processing unknown operation src:127.0.0.136479 dst:127.0.0.150010
- github 生成配置ssh 秘钥方法详解
- Simplest Python K-Way Merging Sort|最简单的Python k路归并排序
- Codeforces Beta Round #19C. Deletion of Repeats
- css兼容问题(一)
- CF446 (Div. 1)简单题解
- TCP的状态转移
- SSM框架搭建总结(2)
- ASP.NET 5 RC 1:UrlRouting 设置(不包含MVC6的UrlRouting设置)
热门文章
- BC#29A:GTY&#39;s math problem(math) B:GTY&#39;s birthday gift(矩阵快速幂)
- 模块讲解----json与pickle模块的区别
- 闪回事务(Flashback Transaction)
- AngularJS 笔记系列(四)控制器和表达式
- WEB前端研发工程师编程能力成长之路(2)
- C# 导出 Excel 的各种方法总结
- 斐讯面试记录—三线程交替打印ABC
- ubuntu apt-get 安装 lnmp
- LRU算法---缓存淘汰算法
- SpringSource Tool Suite (STS)无法启动问题