四数相加 II

88 阅读1分钟

454 四数相加 II

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        //保存满足要求的元组个数
        int res = 0;
        int temp = 0;

        //遍历nums1, nums2 计算两个数组元素之和和次数,其中元素之和为key, 次数为value
        for(int i: nums1) {
            for(int j: nums2) {
                temp = i + j;
                if(map.containsKey(temp)) {
                    map.put(temp, map.get(temp)+1);
                }else {
                    map.put(temp, 1);
                }
            }
        }

        //遍历nums3, nums4计算两个数组元素之和,找到0-两个数组之和的数次数
        for(int k: nums3) {
            for(int l: nums4) {
                temp = k + l;
                if(map.containsKey(0 - temp)){
                    res += map.get(0 - temp);
                }
            }
        }
        return res;
    }
}