题目
给定四个包含整数的数组列表 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 。
例如:
输入: 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
解题
如果直接用4次循环,那么时间复杂度是非常大的。于是采用2个 2次循环,并结合哈希表使用。
python解法
class Solution(object): def fourSumCount(self, nums1, nums2, nums3, nums4): """ :type nums1: List[int] :type nums2: List[int] :type nums3: List[int] :type nums4: List[int] :rtype: int """ # use a dict to store the elements in nums1 and nums2 and their sum hashmap = dict() for n1 in nums1: for n2 in nums2: if n1 + n2 in hashmap: hashmap[n1+n2] += 1 else: hashmap[n1+n2] = 1 # if the -(a+b) exists in nums3 and nums4, we shall add the count count = 0 for n3 in nums3: for n4 in nums4: key = - n3 - n4 if key in hashmap: count += hashmap[key] return count
换种写法(自己写的,实际上是一样的)
class Solution: def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int: res = 0 hush = {} for n1 in nums1: for n2 in nums2: hush[n1+n2] = hush.get(n1+n2,0)+1 for n3 in nums3: for n4 in nums4: value = -n3-n4 if value in hush: res+= hush[value] return res
c++解法
class Solution { public: int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) { unordered_map<int,int> map; for(int n1:nums1){ for(int n2:nums2){ map[n1+n2]++; } } int res=0; for(int n3:nums3){ for(int n4:nums4){ if(map.find(-n3-n4)!=map.end()){ res+=map[-n3-n4]; } } } return res; } };
java解法
class Solution { public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { int res=0; Map<Integer,Integer> mp=new HashMap<>(); for(int i=0;i<nums1.length;i++){ for(int j=0;j<nums2.length;j++){ int s=nums1[i]+nums2[j]; mp.put(s,mp.getOrDefault(s,0)+1); } } for(int i=0;i<nums3.length;i++){ for(int j=0;j<nums4.length;j++){ int s=nums3[i]+nums4[j]; res+=mp.getOrDefault(-s,0); } } return res; } }