问题:
难度:medium
说明:
给出四个数组,将四个数组内拿一个元素,返回四个相加 == 0 的组合个数。
题目连接:https://leetcode.com/problems/4sum-ii/submissions/
输入范围:
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.
输入案例:
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
我的代码:
这个也只是化问题为 2Sum,把集合两两相加即可。使用 map 也挺耗时,因为 500 * 500 * 2 长度数组的时间和空间复杂度,没有特别好的办法,最多弄成数组可以节省点空间。
java-map:
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
int len = A.length, count = 0;
HashMap<Integer,Integer> mapA = new HashMap<Integer,Integer>();
HashMap<Integer,Integer> mapB = new HashMap<Integer,Integer>();
for(int i = 0;i < len;i ++) {
for(int j = 0;j < len;j ++) {
int a = A[i] + B[j];
int b = - C[i] - D[j];
mapA.put(a, mapA.getOrDefault(a, 0) + 1);
mapB.put(b, mapB.getOrDefault(b, 0) + 1);
}
}
for(int value : mapA.keySet())
if(mapB.containsKey(value)) count += mapA.get(value) * mapB.get(value);
return count;
}
}
java-arr:
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
int len = A.length, count = 0, times = len * len;
int AB[] = new int[times];
int CD[] = new int[times];
for(int i = 0;i < len;i ++) {
int slot = i * len;
for(int j = 0;j < len;j ++) {
AB[slot + j] = A[i] + B[j];
CD[slot + j] = - C[i] - D[j];
}
}
Arrays.sort(AB);
Arrays.sort(CD);
int i = 0,j = 0;
A:for(;i < times;) {
for(;j < times;j ++) {
if(AB[i] == CD[j]) {
int ABT = 1, CDT = 1;
while(++ i < times && AB[i] == AB[i - 1]) ABT ++;
while(++ j < times && CD[j] == CD[j - 1]) CDT ++;
count += ABT * CDT;
continue A;
} else if(AB[i] < CD[j]) break;
} i ++;
}
return count;
}
}
c++ arr:
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
int count = 0, len = A.size(), times = len * len;
int *AB = new int[times], *CD = new int[times];
for (int i = 0; i < len; i++) {
int slot = i * len;
for (int j = 0; j < len; j++) {
int site = slot + j;
AB[site] = A[i] + B[j];
CD[site] = -C[i] - D[j];
}
}
sort(AB, AB + times);
sort(CD, CD + times);
int i = 0, j = 0;
A:for (; i < times; ) {
for (; j < times; j++) {
if (AB[i] == CD[j]) {
int ABT = 1, CDT = 1;
while (++i < times && AB[i] == AB[i - 1]) ABT++;
while (++j < times && CD[j] == CD[j - 1]) CDT++;
count += ABT * CDT;
goto A;
} else if(AB[i] < CD[j]) break;
} i++;
}
return count;
}
};