https://leetcode.com/problems/4sum-ii/description/
Solution 1. Save a loop for solution 2.
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
unordered_map<int,int> m1, m2;
for(auto &a : A)
for(auto &b : B) {
m1[a+b]++;
}
int res = 0;
for(auto &c : C)
for(auto &d : D) {
if(m1.count(-(c+d))) res += m1[-(c+d)];
}
return res;
}
Solution 2.
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
unordered_map<int,int> m1, m2;
for(auto &a : A)
for(auto &b : B) {
m1[a+b]++;
}
for(auto &c : C)
for(auto &d : D) {
m2[-(c+d)]++;
}
int res = 0;
for(auto &m : m1) {
if(m2.count(m.first)) res += m.second * m2[m.first];
}
return res;
}
No comments:
Post a Comment