Leetcode454.四数相加II

题目:https://leetcode-cn.com/problems/4sum-ii/

代码:

class Solution {
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        HashMap<Integer, Integer> map = new HashMap<>(A.length * B.length);  // 避免扩容操作,直接初始化一个够用的容量,可以优化运行时间
        for(int i : A){
            for(int j : B){
                map.put(i + j, map.getOrDefault(i + j, 0) + 1);
            }
        }
        int count = 0;
        for(int i : C){
            for(int j : D){
                if(map.containsKey(-1 * (i + j))){
                    count += map.get(-1 * (i + j));
                }
            }
        }
        return count;
    }
}
原文地址:https://www.cnblogs.com/liuyongyu/p/14046673.html