题目地址(454. 四数相加 II)
https://leetcode-cn.com/problems/4sum-ii/
题目描述
给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:0 <= i, j, k, l < nnums1[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 = 02. (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.lengthn == nums2.lengthn == nums3.lengthn == nums4.length1 <= n <= 200-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
前置知识
公司
- 暂无
思路
将4个数相加 拆解成两两相加 第12组相加的和 等于负的第34个数组相加的和 则就将返回值加1
关键点
本题解题步骤:
- 首先定义 一个unordered_map,key放a和b两数之和,value 放a和b两数之和出现的次数。
- 遍历大A和大B数组,统计两个数组元素之和,和出现的次数,放到map中。
- 定义int变量count,用来统计a+b+c+d = 0 出现的次数。
- 在遍历大C和大D数组,找到如果 0-(c+d) 在map中出现过的话,就用count把map中key对应的value也就是出现次数统计出来。
- 最后返回统计值 count 就可以了
代码
- 语言支持:Java
Java Code:
class Solution {public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {HashMap<Integer, Integer> map = new HashMap<>();//保存两数相加的和int temp;//返回的结果int result = 0;for (int i : nums1) {for (int j : nums2) {temp = i+j;//map包含两数相加的和 则将这个key的值+1 反之就讲这个值设置为1if (map.containsKey(temp)) {map.put(temp, map.get(temp)+1);}else {map.put(temp, 1);}}}for (int i : nums3) {for (int j : nums4) {temp = i+j;//后两个数字如果包含与之前数字相加=0的数字则将最终返回结果+=这个数字存储的value值//假设 12数组是 1+2 = 3 34数组的值如果是-3 这时 0 - -3 = 3 就对应上了if (map.containsKey(0 - temp)) {result += map.get(0 - temp);}}}return result;}}
复杂度分析
令 n 为数组长度。
- 时间复杂度:
#card=math&code=O%28n%5E2%29&id=sB3KD)
- 空间复杂度:
