leetcode 454. 4Sum II

本文介绍了一种解决特定四数求和问题的有效算法。该算法利用哈希表(unordered_map)来记录部分求和结果,进而高效地查找匹配项以达到目标和。通过实例演示了如何快速找到使四个整数之和等于零的所有组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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

解题思路:

做这道题我最开始的想法是dp,可发现几乎无法解,仔细观察题目,若四元组求和为0,那么必然存在两组元素之间的对应关系为绝对值相同。这样,我们分别对其中两组数据进行求和,再进行比较,就可以得出解。
注意这里比较的思想是用map来实现的,本文代码里使用了 unordered_map,类似Java的 hashmap,关于和普通map的区别请自行搜索,实现代码如下(C++ 11):

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {

        unordered_map<int,int> valMap;
        for(vector<int>::size_type i = 0;i<A.size();++i)
            for(vector<int>::size_type j = 0;j<B.size();++j) {
                valMap[A[i]+B[j]]++;
            }
        int count = 0;
         for(vector<int>::size_type i = 0;i<C.size();++i)
            for(vector<int>::size_type j = 0;j<D.size();++j) {
                auto findIter = valMap.find(-(C[i]+D[j]));
                if(findIter!=valMap.end()) {
                    count+=findIter->second;
                }
            }
        return count;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值