welcome to my blog
LeetCode Top Interview Questions 454. 4Sum II (Java版; Meidum)
题目描述
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that
A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in
the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.
Example:
Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]
Output:
2
Explanation:
The two tuples are:
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
第一次做; 把下面的写法稍微整理一下, 看起来更简洁; 核心:把four sum转成two sum
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
HashMap<Integer, Integer> sumAB = new HashMap<>();
for(int a: A){
for(int b: B){
int sum = a+b;
sumAB.put(sum, sumAB.getOrDefault(sum,0)+1);
}
}
int count=0;
for(int c:C){
for(int d:D){
int cur = -c-d;
if(sumAB.containsKey(cur))
count+=sumAB.get(cur);
}
}
return count;
}
}
第一次做; 两个两个的处理, 相当于将four sum转成了two sum; 时间复杂度O(N^2), 空间复杂度O(N^2)
//两个两个弄, 相当于转换成了two sum问题
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
//key是ab的求和结果, value是这个结果出现的次数
HashMap<Integer, Integer> ab = new HashMap<>();
int count=0;
for(int a=0; a<A.length; a++){
for(int b=0; b<B.length; b++){
int sum = A[a] + B[b];
ab.put(sum, ab.getOrDefault(sum, 0)+1);
}
}
for(int c=0; c<C.length; c++){
for(int d=0; d<D.length; d++){
int sum = C[c] + D[d];
int cur = - sum;
if(ab.containsKey(cur))
count += ab.get(cur);
}
}
return count;
}
}
第一次做; 暴力; 超时46/48; 需要用空间换时间; 时间复杂度O(N^4), 空间复杂度O(1)
//暴力, 四层循环
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
int count = 0;
for(int a=0; a<A.length; a++){
for(int b=0; b<B.length; b++){
for(int c=0; c<C.length; c++){
for(int d=0; d<D.length; d++){
if(A[a]+B[b]+C[c]+D[d]==0)
count++;
}
}
}
}
return count;
}
}