454. 4Sum II
作者:互联网
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
给定4个整型数组A、B、C、D,统计有多少个4元组(i,j,k,l),使它们满足A[i]+B[j]+C[k]+D[l]等于0。
为简化问题,假定这3个数组均含N个元素,且 0<=N<=500。各数组所含的元素均在(-2)^28到(2^28-1)之间。且结果不超过(2^31-1)。
分析:
这道题按我自己的想法是依次遍历各个数组,当然这是很蠢的,惭愧!最终提交的代码都超时了,就不贴出来了-_-||| 后来参照leetcode的讨论,发现有人提出用两个HashMap分别存储A、B和C、D任意两个元素的和,若第一个map中的某个key,它在相反数(-key)在第二个map中存在,则组成它们的4个数组中的元素的和就是0,而对于本组的4元组的个数,则为key在第一个map中的次数(即key对应的值)与-key在第二个map中的次数。最终代码如下:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { unordered_map<int, int> mp, mp1; for (int a : A) for (int b : B) mp[a + b]++; for (int c : C) for (int d : D) mp1[c + d]++; int rst = 0, tmp = 0; for (auto iter : mp) { tmp = -1 * iter.first; auto it = mp1.find(tmp); if (it != mp1.end()) rst += iter.second * it->second; } return rst; }
标签:4Sum,map,int,454,II,vector,key,mp1,rst 来源: https://www.cnblogs.com/big-potato/p/12269233.html