题目地址
https://leetcode.com/problems/4sum-ii/description/
题目描述
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.
Example:
Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]
Output:
2
Explanation:
The two tuples are:
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
思路
如果按照常规思路去完成查找需要四层遍历,时间复杂是O(n^4), 显然是行不通的。
因此我们有必要想一种更加高效的算法。
我一个思路就是我们将四个数组分成两组,两两结合。
然后我们分别计算两两结合能够算出的和有哪些,以及其对应的个数
。
如图:
这个时候我们得到了两个hashTable
, 我们只需要进行简单的数学运算就可以得到结果。
关键点解析
- 空间换时间
- 两两分组,求出两两结合能够得出的可能数,然后合并即可。
代码
语言支持: JavaScript
,Python3
JavaScript
:
/* * @lc app=leetcode id=454 lang=javascript * * [454] 4Sum II * * https://leetcode.com/problems/4sum-ii/description/ /** * @param {number[]} A * @param {number[]} B * @param {number[]} C * @param {number[]} D * @return {number} */ var fourSumCount = function(A, B, C, D) { const sumMapper = {}; let res = 0; for (let i = 0; i < A.length; i++) { for (let j = 0; j < B.length; j++) { sumMapper[A[i] + B[j]] = (sumMapper[A[i] + B[j]] || 0) + 1; } } for (let i = 0; i < C.length; i++) { for (let j = 0; j < D.length; j++) { res += sumMapper[- (C[i] + D[j])] || 0; } } return res; };
Python3
:
class Solution: def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int: mapper = {} res = 0 for i in A: for j in B: mapper[i + j] = mapper.get(i + j, 0) + 1 for i in C: for j in D: res += mapper.get(-1 * (i + j), 0) return resLeetCode题解45.跳跃游戏 II
给定一个非负整数数组,你最初位于数组的第一个位置。数组中的每个元素代表你在该位置可以跳跃的最大长度。你的目标是使用最少的跳跃次数到达数组的最后一个位置。示例:输入: [2,3,1,1,4]输出: 2解释: 跳到最后一个位置的最小跳跃数是 2。 从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。说明:假设你总是可以到达数…
LeetCode题解113.path-sum-ii题目地址 https://leetcode.com/problems/path-sum-ii/description/ 题目描述 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. Note: A leaf…
LeetCode题解140. 单词拆分 II批注: 由于"可以重复使用字典中的单词", 因此稍微难一点定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。说明:分隔时可以重复使用字典中的单词。你可以假设字典中没有重复的单词。示例 1:输入:s = "catsanddog"wordDict = […
LeetCode题解126. 单词接龙 II (Hard)给定两个单词(beginWord 和 endWord)和一个字典 wordList,找出所有从 beginWord 到 endWord 的最短转换序列。转换需遵循如下规则:每次转换只能改变一个字母。转换过程中的中间单词必须是字典中的单词。说明:如果不存在这样的转换序列,返回一个空列表。所有单词具有相同的长度。所有单词只由小写字母组成。字典中不存在重复的单词。…
LeetCode题解1879. Two Sum VII给定一个已经 按绝对值升序排列 的数组,找到两个数使他们加起来的和等于特定数。函数应该返回这两个数的下标,index1必须小于index2。注意返回的值是0-based。请使用双指针完成本题,否则你有可能会被取消比赛资格。注意事项:```- 数据保证nums中的所有数的互不相同的。- nums数组长度≤100000- nums内的数≤1000000000``…