Two halves with a hash map
Time O(n²) Space O(n²)count[a + b] over nums1 × nums2; for each c + d, add count[−(c + d)].
nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]a + b(list)
count(map)
Step 1/3Every sum of one number from nums1 and one from nums2, counted in a map.
import java.util.*;
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer, Integer> count = new HashMap<>();
for (int a : nums1) for (int b : nums2) count.merge(a + b, 1, Integer::sum);
int total = 0;
for (int c : nums3) for (int d : nums4) total += count.getOrDefault(-(c + d), 0);
return total;
}
}Verdict: The meet-in-the-middle idea in its simplest form.