一、题目
Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
Example 1:
Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
Output: 2
Explanation:
The two tuples are:
- (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
- (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0
Example 2:
Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
Output: 1
Constraints:
n == nums1.length
n == nums2.length
n == nums3.length
n == nums4.length
1 <= n <= 200
-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228文章来源:https://www.toymoban.com/news/detail-736564.html
二、题解
传统暴力需要四重for循环,可以拆成两次,先计算a+b的个数,再判断a+b+c+d是否等于0,由此可简化时间复杂度为O(n^2)文章来源地址https://www.toymoban.com/news/detail-736564.html
class Solution {
public:
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
int n1 = nums1.size(),n2 = nums2.size(),n3 = nums3.size(),n4 = nums4.size();
unordered_map<int,int> map;
int res = 0;
//储存a+b
for(int i = 0;i < n1;i++){
for(int j = 0;j < n2;j++){
map[nums1[i] + nums2[j]]++;
}
}
//查找c+d,使a+b+c+d = 0
for(int i = 0;i < n3;i++){
for(int j = 0;j < n4;j++){
if(map.find(-(nums3[i] + nums4[j])) != map.end()) res+= map[-(nums3[i] + nums4[j])];
}
}
return res;
}
};
到了这里,关于LeetCode454. 4Sum II的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!