代码随想录算法训练6day| 454.四数相加II 、 383.赎金信、15. 三数之和 、18. 四数之和、1. 两数之和 。

前言:只做了四数相加II

四数相加II 

主要思路:我们需要判断的是四个数组中的和为零的情况,对位置并没有要求,所以想到了哈希算法

        1、哈希算法主要来判断在集合中一个元素是否出现

        2、此时数据太过于庞大,需要考虑Map,其中Map用来存AB数组元素相加的所有情况,而key为相加的数值,value为这个值出现的次数。

操作步骤:

        1、遍历AB数组,记录两个数组可能的和与出现的次数放到map中,key为两数和,value为两数和出现的次数

        2、再遍历CD数组,0-(a+b)在map中如果出现,就直接将value出现的次数统计出来,最后输出即可

代码:

#四数相加
class Solution(object):
    def fourSumCount(self, nums1, nums2, nums3, nums4):
        # use a dict to store the elements in nums1 and nums2 and their sum
        hashmap = dict()
        for n1 in nums1:
            for n2 in nums2:
                if n1 + n2 in hashmap:
                    hashmap[n1 + n2] += 1
                else:
                    hashmap[n1 + n2] = 1

        # if the -(a+b) exists in nums3 and nums4, we shall add the count
        count = 0
        for n3 in nums3:
            for n4 in nums4:
                key = - n3 - n4
                if key in hashmap:
                    count += hashmap[key]
        return count

参考资料:

454. 四数相加 II

383. 赎金信

15. 三数之和

18. 四数之和

代码随想录

猜你喜欢

转载自blog.csdn.net/weixin_53333922/article/details/127098216