leetcode454 题目详述 题目详解

英文链接:https://leetcode.com/problems/4sum-ii/

中文链接:https://leetcode-cn.com/problems/4sum-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 。所有整数的范围在 -228 到 228 - 1 之间,最终结果不会超过 231 - 1 。

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
输入:
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

题目详解

  • 运用四重循环暴力枚举的时间复杂度为 O(n^4),效率比较低。
  • 更好的方式是折半,枚举数组 A 和数组 B,运用哈希表存储两者之和 a + b 出现的次数。
  • 再枚举数组 C 和数组 D,在哈希表中查询 -(c + d) 出现的次数,累加到结果中。
  • 时间复杂度为 O(n^2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class  {

public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
Map<Integer, Integer> map = new HashMap<>();
for (int a : A) {
for (int b : B) {
int key = a + b;
map.put(key, map.getOrDefault(key, 0) + 1);
}
}
int res = 0;
for (int c : C) {
for (int d : D) {
res += map.getOrDefault(-(c + d), 0);
}
}
return res;
}
}