454. 四数相加 II
给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。
为了使问题简单化,所有的 A, B, C, D 具有相同的长度 N,且 0 ≤ N ≤ 500 。
最开始我的思路是将最后一个数组的数值存到hash表中,但其实将两组数组的和存入hash map中效率是最高的,具体代码如下(C++版):
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
unordered_map<int,int> numMapAandB;
for(int i : A)
{
for(int j : B)
{
++numMapAandB[i+j];
}
}
int result=0;
for(int i : C)
{
for(int j : D)
{
int tmp=-(i+j);
if(numMapAandB.count(tmp)!=0)
{
result+=numMapAandB[tmp];
}
}
}
return result;
}
};
运行效果:
相同的思路Python代码如下:
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
numMapAandB=dict()
for i in A:
for j in B:
tmp=i+j
if tmp not in numMapAandB:
numMapAandB[tmp]=1
else:
numMapAandB[tmp]+=1
result=0
for i in C:
for j in D:
tmp=-(i+j)
if tmp in numMapAandB:
result+=numMapAandB[tmp]
return result
运行效果(竟然比C++的代码要快,数据结构看来实现方式是有区别的):
下面是Scala的实现代码(开的新坑):
import scala.collection.mutable.Map
object Solution {
def fourSumCount(A: Array[Int], B: Array[Int], C: Array[Int], D: Array[Int]): Int = {
var numMapAandB: Map[Int,Int] = Map()
for(i <- A)
{
for(j <- B)
{
val tmp: Int = i+j
if(!numMapAandB.contains(tmp)) numMapAandB(tmp)=1
else numMapAandB(tmp)+=1
}
}
var result: Int = 0
for(i <- C)
{
for(j <- D)
{
val tmp: Int = -(i+j)
if (numMapAandB.contains(tmp)) result+=numMapAandB(tmp)
}
}
return result
}
}
运行效果:
来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/4sum-ii