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:
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
题目链接:https://leetcode.com/problems/4sum-ii/description/
题目分析:预处理出AB间,CD间任意两个数字的和,对AB预处理出的数组排序,CD中每个值通过二分查找其在AB中相反数的个数,LowerBound函数返回第一个小于等于待查找的数的位置,时间复杂度O(n^2logn)
class Solution {
public int LowerBound(int val, int[] a, int n) {
int l = 0, r = n - 1, mid;
while (l <= r) {
mid = (l + r) >> 1;
if (a[mid] >= val) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return l;
}
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
int n = A.length, N = n * n;
int[] AB = new int[N];
int[] CD = new int[N];
int cntAB = 0, cntCD = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
AB[cntAB++] = A[i] + B[j];
CD[cntCD++] = C[i] + D[j];
}
}
Arrays.sort(AB);
int ans = 0;
for (int i = 0; i < cntCD; i++) {
ans += LowerBound(-CD[i] + 1, AB, cntAB) - LowerBound(-CD[i], AB, cntAB);
}
return ans;
}
}