Appearance
0454-四数相加II
https://leetcode.cn/problems/4sum-ii
给你四个整数数组 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
- -2^28 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 2^28
思路 : 分组 + 哈希表
暴力法,时间复杂度 O(n^4) 会超时
我们将四个数组,两两组合的和加入 Hash 表,如果该和存在则递增1
这样循环后面两组的时候,判断Hash表中是否存在对应的差值,是的话,结果递增1,并且累计结果
参考代码
csharp
public class Solution {
public int FourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Dictionary<int,int> dict = new Dictionary<int,int>();
for(int i=0; i<nums1.Length; i++){
for(int j=0; j<nums2.Length; j++){
int sum = nums1[i] + nums2[j];
if(!dict.ContainsKey(sum)){
dict.Add(sum,1);
}
else{
dict[sum]++;
}
}
}
int max = 0;
for(int i=0; i<nums3.Length; i++){
for(int j=0; j<nums4.Length; j++){
int sum = nums3[i]+nums4[j];
int preSum = 0 - sum;
if(dict.ContainsKey(preSum)){
max += dict[preSum];
}
}
}
return max;
}
}
AlgoPress