LeetCode 454: 四数相加 II 4Sum II
- 2019 年 12 月 16 日
- 笔记
题目:
给定四个包含整数的数组列表 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 。所有整数的范围在 -228 到 228 – 1 之间,最终结果不会超过 231 – 1 。
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l)
there are such that A[i] + B[j] + C[k] + D[l]
is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 – 1 and the result is guaranteed to be at most 231 – 1.
例如:
输入: A = [ 1, 2] B = [-2,-1] C = [-1, 2] D = [ 0, 2] 输出: 2 解释: 两个元组如下: 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
解题思路:
- 暴力破解: 四层 for 循环, 把每一种组合都过一遍. 时间复杂度为 O(n^4)
- 优化一: 使用一个哈希集合存储其中的一个数组, 三层 for 循环把剩下三个数组的组合都过一遍, 并查询哈希集合中是否存在能满足条件的元素值存在. 时间复杂度为 O(n^3)
- 优化二: 使用一个哈希映射, key 为两个数组中元素组合值之和, value 为两数和的值出现的次数(因为任意元素组合之和可能相同), 两层 for 循环将剩余两个数组所有组合过一遍, 找到满足条件的 key , 总次数与对应 value 值累加, 最优解, 时间复杂度为 O(n^2)
哈希映射解题:
Java:
class Solution { public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { Map<Integer, Integer> map = new HashMap<>(); int count = 0; for (int i = 0; i < A.length; i++) for (int j = 0; j < B.length; j++) { int sum = A[i] + B[j]; map.put(sum, map.getOrDefault(sum, 0) + 1); // key 为两个数组中元素组合值之和, value 为两数和的值出现的次数 } for (int i = 0; i < C.length; i++) for (int j = 0; j < D.length; j++) count += map.getOrDefault(-C[i] - D[j], 0); // 找到满足条件的 key , 总次数与对应 value 值累加 (因为value 代表 A, B 数组中符合条件的组合的次数) return count; } }
Python:
class Solution: def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int: count, hash_map = 0, dict() for a in A: for b in B: sum_ab = a+b hash_map.setdefault(sum_ab, 0) hash_map[sum_ab] += 1 # key 为两个数组中元素组合值之和, value 为两数和的值出现的次数 for c in C: for d in D: count += hash_map.get(-c-d, 0) # 找到满足条件的 key , 总次数与对应 value 值累加 (因为value 代表 A, B 数组中符合条件的组合的次数) return count