[LeetCode] 4Sum II

454. 4Sum II

Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that:

  • 0 <= i, j, k, l < n
  • nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
int res = 0;
unordered_map<int, int> tmp1, tmp2, s1;
for(auto& n: A) tmp1[n]++;
for(auto& n: B) {
for(auto& [k, v]: tmp1) {
s1[k+n]+=v;
}
}
for(auto& n: C) tmp2[n]++;
for(auto& n: D) {
for(auto& [k, v]: tmp2) {
res += s1[-(k+n)] * v;
}
}

return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/03/PS/LeetCode/4sum-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.