当前位置:网站首页>LeetCode 454. 四数相加 II
LeetCode 454. 四数相加 II
2022-07-01 11:54:00 【碳烤小肥羊。。。】
题目描述:给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
示例 1:
输入:nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
输出:2
解释:
两个元组如下:
1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0
示例 2:
输入:nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
输出:1
提示:
n == nums1.length
n == nums2.length
n == nums3.length
n == nums4.length
1 <= n <= 200
-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
思路解析:
- 首先定义 一个map集合,key放a和b两数之和,value 放a和b两数之和出现的次数。
- 遍历num1和nums2数组,统计两个数组元素之和,和出现的次数,放到map中。
- 定义int变量res,用来统计 a+b+c+d = 0 出现的次数。
- 在遍历nums3和nums4数组,找到如果 0-(c+d) 在map中出现过的话,就用res把map中key对应的value也就是出现次数统计出来。
- 最后返回统计值 res就可以了
代码实现:
public static int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4){
Map<Integer, Integer> map = new HashMap<>();
int temp;
int res = 0;
// 统计两个数组中的元素之和,同时统计出现的次数, 放入map
for(int i : nums1){
for(int j : nums2){
temp = i + j;
if(map.containsKey(temp)){
map.put(temp, map.get(temp) + 1);
}else {
map.put(temp, 1);
}
}
}
// 统计剩下的两个元素的和,在map中找是否存在相加为0的情况,同时记录次数
for(int i : nums3){
for(int j : nums4){
temp = i + j;
if(map.containsKey(0 - temp)){
res += map.get(0-temp)
}
}
}
return res;
}
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/4sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
边栏推荐
猜你喜欢
Learning summary on June 28, 2022
Exploration and practice of inress in kubernetes
华为HMS Core携手超图为三维GIS注入新动能
Computer graduation project asp Net hotel room management system VS development SQLSERVER database web structure c programming computer web page source code project
Redis' attack tactics
Redis的攻击手法
Binary stack (I) - principle and C implementation
谈思生物直播—GENOVIS张洪妍抗体特异性酶切技术助力抗体药物结构表征
Deep understanding of grpc part1
Prepare for the Blue Bridge Cup Day10__ PWM control light brightness
随机推荐
陈珙:微服务,它还那么纯粹吗?
Activity workflow engine
sshd_config 中 PermitRootLogin 的探讨
redis配置环境变量
Interpretation of R & D effectiveness measurement framework
[classic example] classic list questions @ list
Redis startup and library entry
Kernel synchronization mechanism
redis中value/SortedSet
Acly and metabolic diseases
Test case writing specification in unittest framework and how to run test cases
MQ-防止消息丢失及重复消费
Theoretical basis of graph
Learning summary on June 28, 2022
Computer graduation project asp Net attendance management system vs developing SQLSERVER database web structure c programming computer web page source code project
Comment Cao définit la décimale de dimension
Why must we move from Devops to bizdevops?
I'm in Zhongshan. Where is a better place to open an account? Is it actually safe to open an account online?
Adjacency matrix undirected graph (I) - basic concepts and C language
Force button homepage introduction animation