Leetcode 每日一题——454. 四数相加 II

454. 四数相加 II

给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。

为了使问题简单化,所有的 A, B, C, D 具有相同的长度 N,且 0 ≤ N ≤ 500 。
在这里插入图片描述
最开始我的思路是将最后一个数组的数值存到hash表中,但其实将两组数组的和存入hash map中效率是最高的,具体代码如下(C++版):

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        unordered_map<int,int> numMapAandB;
        for(int i : A)
        {
            for(int j : B)
            {
                ++numMapAandB[i+j];
            }
        }
        int result=0;
        for(int i : C)
        {
            for(int j : D)
            {
                int tmp=-(i+j);
                if(numMapAandB.count(tmp)!=0)
                {
                    result+=numMapAandB[tmp];
                }
            }
        }
        return result;

    }
};

运行效果:
在这里插入图片描述
相同的思路Python代码如下:

class Solution:
    def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
        numMapAandB=dict()
        for i in A:
            for j in B:
                tmp=i+j
                if tmp not in numMapAandB:
                    numMapAandB[tmp]=1
                else:
                    numMapAandB[tmp]+=1
        result=0
        for i in C:
            for j in D:
                tmp=-(i+j)
                if tmp in numMapAandB:
                    result+=numMapAandB[tmp]    
        return result

运行效果(竟然比C++的代码要快,数据结构看来实现方式是有区别的):
在这里插入图片描述
下面是Scala的实现代码(开的新坑):

import scala.collection.mutable.Map
object Solution {
    def fourSumCount(A: Array[Int], B: Array[Int], C: Array[Int], D: Array[Int]): Int = {
        var numMapAandB: Map[Int,Int] = Map()
        for(i <- A)
        {
            for(j <- B)
            {
                val tmp: Int = i+j

                if(!numMapAandB.contains(tmp)) numMapAandB(tmp)=1

                else numMapAandB(tmp)+=1
            }
        }
        var result: Int = 0
        for(i <- C)
        {
            for(j <- D)
            {
                val tmp: Int = -(i+j)
                if (numMapAandB.contains(tmp)) result+=numMapAandB(tmp)
            }
        }
        return result
    }
}

运行效果:
在这里插入图片描述

来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/4sum-ii

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值