MENU

LeetCode454. 4Sum II(思维)

2019 年 02 月 17 日 • 阅读: 979 • LeetCode阅读设置

LeetCode454. 4Sum II(思维)

  • Medium
  • Accepted:56,454
  • Submissions:113,653

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

链接

https://leetcode.com/problems/4sum-ii/

题意

给定四个整型数组A、B、C、D,计算满足$A[i]+B[j]+C[k]+D[l]=0$的四元组$(i,j,k,l)$的数量,数组长度在500以内,答案在整型范围以内。

题解

  • 四重循环暴力,时间复杂度$O(n^4)$
  • 将D中元素放入查找表,使用unordered_map,时间复杂度$O(n^3)$
  • 将C+D的每一种可能放入查找表,时间复杂度$O(n^2)$

代码

  • Runtime: 208 ms, faster than 76.60% of C++ online submissions for 4Sum II.
  • Memory Usage: 28.8 MB, less than 100.00% of C++ online submissions for 4Sum II.
class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        unordered_map <int, int> umap;
        for (int i = 0; i < C.size(); ++i)
            for (int j = 0; j < D.size(); ++j)
                umap[C[i]+D[j]]++;
        int ans = 0;
        for (int i = 0; i < A.size(); ++i)
        {
            for (int j = 0; j < B.size(); ++j)
            {
                int x = -1 * (A[i] + B[j]);
                if (umap.count(x) > 0)
                    ans += umap[x];
            }
        }
        return ans;
    }
};
  • 因为不存在的数默认的值为0,所以无需判断是否在查找表中,直接加即可,简化代码如下:
class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        unordered_map <int, int> umap;
        for (int c : C)
            for (int d : D)
                umap[c + d]++;
        int ans = 0;
        for (int a : A) 
            for (int b : B) 
                ans += umap[-a-b];
        return ans;
    }
};

The end.
2019年2月17日 星期日