【开源】数字化转型实操——非要度
244 2023-04-03 04:23:28
https://leetcode.cn/problems/4sum-ii/
给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
输入:nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
输出:2
解释:
两个元组如下:
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
哈希表来存储12中的和,然后34中的和用来查找哈希表,这样可以确保n2,对于这类问题,可以采用一半一半的方法,如果是6个数组,那就可以用三三分组,n3的复杂度。
时间复杂度 O(n2)空间复杂度 O(n)
Java
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { int n = nums1.length; int ans = 0; HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int s = nums1[i] + nums2[j]; map.put(s, map.getOrDefault(s, 0) + 1); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int s = nums3[i] + nums4[j]; ans += map.getOrDefault(-s, 0); } } return ans; }