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 to - 1 and the result is guaranteed to be at most - 1.
Example:
Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]Output:
2Explanation:
The two tuples are:
- (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
- (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
分析
- 4 层循环暴力搜索,时间复杂度 O(),空间复杂度 O(1).
- 用一个 HashMap 缓存数组 A+B,另一个 HashMap 缓存 C+D,key 为和,value 为和出现的次数,然后用 2 层循环,遍历两个 HashMap,统计和为 0 的次数。该方法时间复杂度 O(),空间复杂度 O(),用空间换取了时间。
- 推广到 k 个数组,也可以用上述方法,用一个 HashMap 缓存前个数组的和,另一个 HashMap 缓存后个数组的和,然后遍历两个 HashMap,统计和为 0 的次数。时间复杂度 O(),空间复杂度 O()。