题目
思路
- 遍历 A 和 B 所有元素和的组合情况,并记录在map 中,map 的 key 为两数和,value 为该两数和出现的次数
遍历 C 和 D 所有元素和的组合情况,取和的负值判断其是否在map 中,若存在则取出 map 对应的 value 值,count = count + value
代码
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {Map<Integer, Integer> map = new HashMap<>();int len = A.length, res = 0;for (int a : A) {for (int b : B) {map.put(a + b, map.getOrDefault(a + b, 0) + 1);}}for (int c : C) {for (int d : D) {int key = -(c + d);if (map.containsKey(key)) {res += map.get(key);}}}return res;}
