【数据结构与算法】leetcode刷题记录(四数之和)---->hashMAP
文章目录四数之和javapython四数之和给定四个包含整数的数组列表 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 。所有整数的范围在 -228 到 228 - 1 之间,最终结果不会超过 231 - 1
·
四数之和
给定四个包含整数的数组列表 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 。所有整数的范围在 -228 到 228 - 1 之间,最终结果不会超过 231 - 1 。
输入:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]
输出:
2
解释:
两个元组如下:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
java
1.hash表:
先分析以下,可以分为两拨进行操作
用hash保存A — >for循环要遍历剩下的三个数组进行判断 -->时间复杂度0(n3)
用hash保存AB — >for循环要遍历剩下的两个数组进行判断 -->时间复杂度0(n2)
用hash保存ABC — >for循环要遍历剩下的一个数组进行判断 -->时间复杂度0(n3)
所以用for循环遍历两个数组,把AB的和放在hashmap中:
class Solution {
public static int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
// 49-->1 48-->0
int res = 0;
int len = A.length;
HashMap<Integer,Integer> mmp = new HashMap<>();
for(int i =0;i<len;i++){
for(int j =0;j<len;j++){
int sumAB = A[i]+B[j];
if(mmp.containsKey(sumAB)){
mmp.put(sumAB,mmp.get(sumAB)+1);
}else{
mmp.put(sumAB,1);
}
}
}
for(int i =0;i<len;i++){
for(int j =0;j<len;j++){
int sumCD = -(C[i]+D[j]);
if(mmp.containsKey(sumCD)){
res+=mmp.get(sumCD);
}
}
}
return res;
}
}
python
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
res = 0
dict1 = {}
for i in range(0,len(A)):
for j in range(0,len(A)):
sumAB = A[i]+B[j]
if sumAB in dict1:
dict1[sumAB]+=1
else:
dict1[sumAB] = 1
for i in range(0, len(A)):
for j in range(0, len(A)):
sumCD = -(C[i]+D[j])
if sumCD in dict1.keys():
res+=dict1[sumCD]
return res
点击阅读全文
更多推荐
目录
所有评论(0)