原题链接: https://leetcode.com/problems/4sum-ii/
1. 题目介绍
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.
给定4个数组A、B、C、D,每个数组抽出一个数字,这四个数组加起来的和需要为0。也就是A[i] + B[j] + C[k] + D[l] = 0.求满足上述条件的 (i, j, k, l) 四元数组有多少个。
为了让问题简单一些,所有的A、B、C、D四个数组长度都是N,0 ≤ N ≤ 500。数组内所有的整数范围是[-228 , 228-1 ],满足条件的 (i, j, k, l) 个数不超过 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
2. 解题思路
如果采用暴力搜索的方法,时间复杂度是O(N4)。如果借助HashMap,可以将时间复杂度降低为O(N2)。
首先将A、B两个数组所有的和都存放在HashMap里面,key是和的值,value是该值出现的次数。
然后计算C、D两个数组所有可能出现的值,将C[k] + D[l]的和取负数,判断在HashMap里面有没有,如果有的话,就将对应的value值加入结果中。
实现代码
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
Map<Integer, Integer> map = new HashMap();
for(int x: A){
for(int y : B){
map.put(x+y, map.getOrDefault(x+y, 0) + 1);
}
}
int ans = 0;
for(int x: C){
for(int y : D){
ans+=map.getOrDefault(-(x+y), 0);
}
}
return ans;
}
}
3. 参考链接
https://leetcode-cn.com/problems/4sum-ii/solution/java-shi-yong-map-by-zxy0917-4/
https://blog.csdn.net/qq_26410101/article/details/80721017
本文针对LeetCode上的4Sum II问题,提出了利用HashMap优化搜索效率的解决方案,将时间复杂度从O(N^4)降低到O(N^2),并通过具体示例详细解释了实现过程。

1371

被折叠的 条评论
为什么被折叠?



