【哈希表】leetcode454.四数相加II(C/C++/Java/Python/Js)


需要哈希的地方都能找到map的身影

1 题目

题源链接
给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:

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

在这里插入图片描述


2 思路

暴力想法是:四个for循环循环四个数组分别相加,显然时间复杂度是O(n4)。

这道题目是四个独立的数组,只要找到A[i] + B[j] + C[k] + D[l] = 0就可以,不用考虑有重复的四个元素相加等于0的情况, 所以相对于题目18. 四数之和,题目15.三数之和,还是简单了不少!

本题解题步骤:

  1. 首先定义 一个unordered_map,key放a和b两数之和,value 放a和b两数之和出现的次数。
  2. 遍历大A和大B数组,统计两个数组元素之和,和出现的次数,放到map中。
  3. 定义int变量count,用来统计 a+b+c+d = 0 出现的次数。
  4. 在遍历大C和大D数组,找到如果 0-(c+d) 在map中出现过的话,就用count把map中key对应的value也就是出现次数统计出来。
  5. 最后返回统计值 count 就可以了

是不是很妙!!!
如果还没有get到可以看Carl哥的视频讲解


3 代码

3.1 C++版本

class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
        //不需要排序所以使用unordered_map
        unordered_map<int, int> mapAB ; //key:a+b的值  value:a+b数值对应出现次数
        for (int a : nums1) {
            for (int b : nums2) {
                mapAB[a + b] ++;
            }
        }
        int count = 0;  //记录满足条件四元组数量
        for (int c : nums3) {
            for (int d : nums4) {
                if (mapAB.find(0 - (c + d)) != mapAB.end())
                    count += mapAB[0 - (c + d)];
            }
        }
        return count;
    }
};

3.2 C版本

struct hashTable {
    int key;
    int val;
    UT_hash_handle hh;
};

int fourSumCount(int* A, int ASize, int* B, int BSize, int* C, int CSize, int* D, int DSize) {
    struct hashTable* hashtable = NULL;
    for (int i = 0; i < ASize; ++i) {
        for (int j = 0; j < BSize; ++j) {
            int ikey = A[i] + B[j];
            struct hashTable* tmp;
            HASH_FIND_INT(hashtable, &ikey, tmp);
            if (tmp == NULL) {
                struct hashTable* tmp = malloc(sizeof(struct hashTable));
                tmp->key = ikey, tmp->val = 1;
                HASH_ADD_INT(hashtable, key, tmp);
            } else {
                tmp->val++;
            }
        }
    }
    int ans = 0;
    for (int i = 0; i < CSize; ++i) {
        for (int j = 0; j < DSize; ++j) {
            int ikey = -C[i] - D[j];
            struct hashTable* tmp;
            HASH_FIND_INT(hashtable, &ikey, tmp);
            if (tmp != NULL) {
                ans += tmp->val;
            }
        }
    }
    return ans;
}

3.3 Java版本

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Map<Integer, Integer> mapAB = new HashMap<>(); //key:nums1和nums2中元素相加的值 value:出现次数
        int tmp, count=0; //count存放符合条件四元组的次数
        for (int a : nums1) {
            for (int b : nums2) {
                tmp = a + b;
                if (mapAB.containsKey(tmp))
                    mapAB.put(tmp, mapAB.get(tmp) + 1);
                else
                    mapAB.put(tmp, 1);
            }
        }
        for (int c : nums3) {
            for (int d : nums4) {
                tmp = c + d;
                if (mapAB.containsKey(0 - tmp))
                    count += mapAB.get(0 - tmp);
            }
        }
        return count;
    }
}

3.4 Python版本

class Solution(object):
    def fourSumCount(self, nums1, nums2, nums3, nums4):
        # 用字典存储 nums1和nums2中元素之和,value为出现次数
        mapAB = dict()
        for a in nums1:
            for b in nums2:
                if a + b in mapAB:
                    mapAB[a + b] += 1
                else:
                    mapAB[a + b] = 1
        count = 0   #存放符合条件四元组数量
        for c in nums3:
            for d in nums4:
                tmp = 0 - (c + d)
                if tmp in mapAB:
                    count += mapAB[tmp]
        return count

3.5 JavaScript版本

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @param {number[]} nums3
 * @param {number[]} nums4
 * @return {number}
 */
var fourSumCount = function(nums1, nums2, nums3, nums4) {
    const twoSumMap = new Map();
    let count = 0;
    // 统计nums1和nums2数组元素之和,和出现的次数,放到map中
    for(const n1 of nums1) {
        for(const n2 of nums2) {
            const sum = n1 + n2;
            twoSumMap.set(sum, (twoSumMap.get(sum) || 0) + 1)
        }
    }
    // 找到如果 0-(c+d) 在map中出现过的话,就把map中key对应的value也就是出现次数统计出来
    for(const n3 of nums3) {
        for(const n4 of nums4) {
            const sum = n3 + n4;
            count += (twoSumMap.get(0 - sum) || 0)
        }
    }

    return count;
};

4 总结

时间复杂度:O(n2)。我们使用了两次二重循环,时间复杂度均为 O(n2)。在循环中对哈希映射进行的修改以及查询操作的期望时间复杂度均为 O(1),因此总时间复杂度为 O(n2)。

空间复杂度:O(n2),即为哈希映射需要使用的空间。在最坏的情况下,A[i]+B[j]A[i]+B[j] 的值均不相同,因此值的个数为 n2 ,也就需要 O(n2) 的空间。

看到形如:A+B…+N=0的式子,要转换为(A+…T)=-((T+1)…+N)再计算,这个T的分割点一般是一半,特殊情况下需要自行判断。定T是解题的关键。

如果还没有get到可以看Carl哥的视频讲解

By – Suki 2023/1/31

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值