454.四数相加II

势如破雾 发布于 2025-08-09 100 次阅读


题目

454. 四数相加 II - 力扣(LeetCode)

给你四个整数数组 nums1nums2nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:

  • 0 <= i, j, k, l < n
  • nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0

示例 1:

输入:nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
输出:2
解释:
两个元组如下:
1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0

示例 2:

输入:nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
输出:1

  提示:

  • n == nums1.length
  • n == nums2.length
  • n == nums3.length
  • n == nums4.length
  • 1 <= n <= 200
  • -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228

题解

暴力解肯定是4次方复杂度了。我们可以把4个for拆成两个。nums1和nums2for循环计算各个结果然后放入map1<int,int>中,map1的key为结果值,value为次数。nums3和num4for循环计算放入map2中。之后遍历map1的各个结果时,看map2中是否有-key,如果有则次数相乘。遍历结束返回次数。

    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
                unordered_map<int,int> records_ab;
        for(int num1:nums1){
            for(int num2:nums2){
                int sum=num1+num2;
                if(records_ab.find(sum)!=records_ab.end()){
                    records_ab.find(sum)->second++;
                }else{
                    records_ab.insert({sum,1});
                }
            }
        }
        unordered_map<int,int> records_cd;
        for(int num3:nums3){
            for(int num4:nums4){
                int sum=num3+num4;
                if(records_cd.find(sum)!=records_cd.end()){
                    records_cd.find(sum)->second++;
                }else{
                    records_cd.insert({sum,1});
                }
            }
        }
        int sum=0;
        for(auto it:records_ab){
            if(records_cd.find(-it.first)!=records_cd.end()){
                sum=sum+it.second*records_cd.find(-it.first)->second;
            }
        }
        return sum;
    }
研究生在读,喜欢尝试新鲜事物,学习技术。爱好跑步,拳击,爬山。
最后更新于 2025-08-09