[LeetCode] 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) + (-1) + 0 = 0

 

這道題是之前那道 4Sum 的延伸,讓我們在四個數組中各取一個數字,使其和為0。那么墜傻的方法就是遍歷所有的情況,時間復雜度為 O(n4)。但是既然 Two Sum 那道都能將時間復雜度縮小一倍,那么這道題使用 HashMap 是否也能將時間復雜度降到 O(n2) 呢?答案是肯定的,如果把A和B的兩兩之和都求出來,在 HashMap 中建立兩數之和跟其出現次數之間的映射,那么再遍歷C和D中任意兩個數之和,只要看哈希表存不存在這兩數之和的相反數就行了,參見代碼如下:

 

解法一:

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        int res = 0;
        unordered_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]];
            }
        }
        for (int i = 0; i < C.size(); ++i) {
            for (int j = 0; j < D.size(); ++j) {
                int target = -1 * (C[i] + D[j]);
                res += m[target];
            }
        }
        return res;
    }
};

 

下面這種方法用了兩個 HashMap 分別記錄 AB 和 CB 的兩兩之和出現次數,然后遍歷其中一個 HashMap,並在另一個 HashMap 中找和的相反數出現的次數,參見代碼如下:

 

解法二:

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        int res = 0, n = A.size();
        unordered_map<int, int> m1, m2;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                ++m1[A[i] + B[j]];
                ++m2[C[i] + D[j]];
            }
        }
        for (auto a : m1) res += a.second * m2[-a.first];
        return res;
    }
};

 

類似題目:

4Sum

 

參考資料:

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

https://leetcode.com/problems/4sum-ii/discuss/93920/Clean-java-solution-O(n2)

https://leetcode.com/problems/4sum-ii/discuss/93925/Concise-C%2B%2B-11-code-beat-99.5

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM