leetcode-454-4Sum-II

描述


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:

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

分析


这道题虽然打着 4 Sum 的旗号,实际上思路还是不太一样,这道题可以用哈希表来做,时间复杂度是 $O(n)$,代码也要简单一点,先把 A 和 B 的两两之和都存储哈希表中,然后遍历 C 和 D 的两两之和,如果哈希表中存在这两个数之和的相反数,则结果加一。

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
Map<Integer, Integer> map = new HashMap<>();
int result = 0;

for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
map.put(A[i] + B[j], map.getOrDefault(A[i] + B[j], 0) + 1);
}
}

for (int i = 0; i < C.length; i++) {
for (int j = 0; j < D.length; j++) {
result += map.getOrDefault(-1 * (C[i]+D[j]), 0);
}
}
return result;
}
}

相关问题


题目来源