Leetcode 454. 4Sum II
程序员文章站
2024-01-17 23:42:28
...
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:
- (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
- (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
method 1 转化为3Sum
做过前面的题的思想就会想到将4Sum转化为3Sum,但这个方法会TLE
int fourSumCount3(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
int count = 0;
unordered_map<int, vector<int>> map;
for (int i = 0; i < D.size(); i++){
vector<int> v;
if (!map.count(D[i])){
v.push_back(i);
map[D[i]] = v;
}
else{
v = map[D[i]];
v.push_back(i);
map[D[i]] = v;
}
}
for (int i = 0; i < A.size(); i++){
for (int j = 0; j < B.size(); j++){
for (int k = 0; k < C.size(); k++){
int sum3 = A[i] + B[j] + C[k];
if (map.count(-sum3)){
vector<int> index = map[-sum3];
count += index.size();
}
}
}
}
return count;
}
method 2 合并数组转化为2Sum
因为本题只需要返回count,而不需要返回具体每个数组相应的索引,因此我们可以将4个数组合并为两个数组,同时记录相同值的个数,然后4Sum就会转化为2Sum。
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
unordered_map<int, int> map1;
unordered_map<int, int> map2;
for (int i = 0; i < A.size(); i++)
{
for (int j = 0; j < B.size(); j++)
{
//for map1
int sumAB = A[i] + B[j];
if (!map1.count(sumAB)){
map1[sumAB] = 1;
}
else map1[sumAB]++;
//for map2
int sumCD = C[i] + D[j];
if (!map2.count(sumCD)){
map2[sumCD] = 1;
}
else map2[sumCD]++;
}
}
int count = 0;
unordered_map<int, int>::iterator iter = map1.begin();
for (; iter != map1.end(); iter++)
{
int sumAB = iter->first;
if (map2.count(-sumAB)) count += (iter->second * map2[-sumAB]);
}
return count;
}
method 3 binary Search
本题如果要使用二分查找,也是同样的思路,在ABsum的vector遍历,然后再CDsum的vector中二分查找,只是要考虑下如何再二分查找中统计相同的所有个数
和2Sum中的binary Search差不多
summary
- 用binary Search在一个有序序列中查找某一个数
推荐阅读
-
Leetcode 454. 4Sum II
-
【LeetCode】 119. 杨辉三角 II 不正经的骚操作
-
LeetCode第219题--存在重复元素II
-
#leetcode刷题之路45-跳跃游戏 II
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST
-
LeetCode454题四数相加 II
-
#leetcode刷题之路40-组合总和 II
-
LeetCode 33. Search in Rotated Sorted Array && 81. Search in Rotated Sorted Array II
-
LeetCode 63. 不同路径 II
-
[leetcode]63. 不同路径 II