454. 四数相加 II
这道题刚开始看的时候感觉做的来,但是写的时候却不知道如何下笔,有点怀疑自己的思路。
然后看了卡哥思路,卡哥是首先把这四个数组分成了两份,每份两个。
卡哥对于这题的视频讲解很详细,其中也讲到了为什么不是一三分,而是二二分,主要是从时间复杂度上考虑的,二二分能让时间复杂度是O(n^2),而一三分的时间复杂度是O(n^3)。
看了卡哥视频讲解后写的代码:
class Solution {
public:
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
unordered_map<int, int> map1;
unordered_map<int, int> map2;
for (auto n1 : nums1)
{
for (auto n2 : nums2)
{
int sum = n1 + n2;
auto iter = map1.find(sum);
if (iter != map1.end())
iter->second += 1;
else
map1.insert(pair<int, int>(sum, 1));
}
}
for (auto n3 : nums3)
{
for (auto n4 : nums4)
{
int sum = n3 + n4;
auto iter = map2.find(sum);
if (iter != map2.end())
iter->second += 1;
else
map2.insert(pair<int, int>(sum, 1));
}
}
int cnt = 0;
for (auto m : map1)
{
auto iter = map2.find(-m.first);
if (iter != map2.end())
cnt += m.second * iter->second;
}
return cnt;
}
};
卡哥写的代码:
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
unordered_map<int, int> umap; //key:a+b的数值,value:a+b数值出现的次数
// 遍历大A和大B数组,统计两个数组元素之和,和出现的次数,放到map中
for (int a : A) {
for (int b : B) {
umap[a + b]++;
}
}
int count = 0; // 统计a+b+c+d = 0 出现的次数
// 再遍历大C和大D数组,找到如果 0-(c+d) 在map中出现过的话,就把map中key对应的value也就是出现次数统计出来。
for (int c : C) {
for (int d : D) {
if (umap.find(0 - (c + d)) != umap.end()) {
count += umap[0 - (c + d)];
}
}
}
return count;
}
};
卡哥代码果然简洁,思路和我写的代码略微有点不同,不过从卡哥代码中知道了原来map的元素可以类似像数组那样引用,所以我在处理元素相加的时候写复杂了。

浙公网安备 33010602011771号