【LeetCode】454. 4Sum II 四数相加 II(Medium)(JAVA)
题目地址: https://leetcode.com/problems/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 -2^28 to 2^28 - 1 and the result is guaranteed to be at most 2^31 - 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
题目大意
给定四个包含整数的数组列表 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 。所有整数的范围在 -2^28 到 2^28 - 1 之间,最终结果不会超过 2^31 - 1 。
解题方法
- 先用一个 map 把 C 和 D 和的结果和出现次数保存起来
- 再用两个 for 循环把 A 和 B 的结果反过来查看 map 中是否有 C 和 D 的结果,并取出出现次数,把次数累加到结果当中
- note: 算法复杂度 O(n^2),而且题目也指明了:所有整数的范围在 -2^28 到 2^28 - 1 之间,最终结果不会超过 2^31 - 1 。所以不用担心 int 超限的问题
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
int res = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < C.length; i++) {
for (int j = 0; j < D.length; j++) {
int sum = C[i] + D[j];
Integer count = map.get(sum);
if (count == null) {
map.put(sum, 1);
} else {
map.put(sum, count + 1);
}
}
}
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
Integer count = map.get(- A[i] - B[j]);
if (count != null) res += count;
}
}
return res;
}
}
执行耗时:70 ms,击败了87.36% 的Java用户
内存消耗:57.4 MB,击败了65.36% 的Java用户