leetcode 4Sum II

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 4Sum II相关的知识,希望对你有一定的参考价值。

454. 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 -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) +

跟之前写的TwoSum一样使用哈希表即可简化计算时间复杂度的水题
题目固定的给出A B C D四行需要4行中的列的组合为0,时间复杂度为o(\(n4\))但是和为0等价于有两个相反数存在,所以将其分为AB一组, CD一组即可.时间复杂度为O(\(n^2\))

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        map<int, int>m;
        for(int i = 0; i<A.size(); i++){
            for(int j=0; j<B.size(); j++){
                m[A[i]+B[j]]++;
            }
        }
        int resultNum  = 0;
        for(int i = 0; i<C.size(); i++){
            for(int j =0; j<D.size(); j++){
                int reverse = C[i]+D[j];
                resultNum += m[-1*reverse];
            }
        }
        return resultNum;
    }
};







以上是关于leetcode 4Sum II的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 4Sum II

[LeetCode] 454. 4Sum II 四数之和II

LeetCode454 4Sum II

Leetcode_454_4Sum II

题目地址(4sum-ii/“>454. 四数相加 II)

454. 4Sum II