4 个数的和 II

1. LeetCode 454: 4 Sum II

2. 描述:

给定四组整数数组A,B,C,D,计算满足A[i] +B [j] + C[k] + D[l] = 0的(i, j, k, l)的数量。

3. 示例 :

输入:
    A = [ 1, 2]
    B = [-2,-1]
    C = [-1, 2]
    D = [ 0, 2]

输出:
    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

4. 解决方案:

void VectorSum(vector<int>& A, vector<int>& B, unordered_map<int,int>& sum){
    for(auto& a: A){
        for(auto& b: B){
            sum[a + b]++;
        }
    }
}
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
    unordered_map<int,int> sum1,sum2;
    VectorSum(A, B, sum1);
    VectorSum(C, D, sum2);
    int result = 0;
    for(auto& iter1: sum1){
        if(sum2.count(-iter1.first)){
            result += iter1.second * sum2[-iter1.first];
        }
    }
    return result;
}
Table of Contents