Loading

454. 四数相加 II

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

因为要求的是元组的数量
思路:
拿两个数组各个元素进行求和,加到map中,剩下的两个数组加和,看有没有符合条件的,有的话,统计次数

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Map<Integer,Integer> map = new HashMap<>();
        int temp = 0, res = 0;
        for(int i : nums1){
            for(int j : nums2){
                temp = i + j;
                if(map.containsKey(temp)){
                    map.put(temp, map.get(temp) + 1);// 添加对应的key-value这样的组合时,如果原本已经存在对应的key,则直接改变对应的value
                }else{
                    map.put(temp, 1);
                }
            }
        }
        for(int i : nums3){
            for(int j : nums4){
                temp = i + j;
                if(map.containsKey(0 - temp)){
                    res += map.get(0 - temp);
                }
            }
        }
        return res;
    }
}
posted @ 2022-01-16 17:38  Zhbeii  阅读(25)  评论(0)    收藏  举报