代码随想录算法训练营第六天| 454.四数相加 15.三数之和 18.四数之和

发布时间 2023-12-05 20:26:59作者: 梅子酒ya

LeetCode 454.四数相加

题目链接: LeetCode454

思路:  将两个数组中的数存放到一个map中,用另外两个数组的值在map中去减

 

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        unordered_map<int, int> umap; 
        for (int a : A) {
            for (int b : B) {
                umap[a + b]++;
            }
        }
        int count = 0; 
        for (int c : C) {
            for (int d : D) {
                if (umap.find(0 - (c + d)) != umap.end()) {
                    count += umap[0 - (c + d)];
                }
            }
        }
        return count;
    }
};

 

 

LeetCode 15.三数之和

题目链接: LeetCode15

思路:

 

 

 

LeetCode 18.四数之和

题目链接:  LeetCode18

思路: