454. 四数相加 II---leetcode

454四数相加

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Map<Integer,Integer> map=new HashMap<>();
        /*哈希表
        * Map   key值存储A和B的和,value存储这个和出现的次数*/
        int temp;
        int res=0;
        for (int A:nums1){
            for (int B:nums2){
                temp=A+B;
                if (map.containsKey(temp)){
                    map.put(temp,map.get(temp)+1)
                }else{
                    map.put(temp,1);
                }
                /*如果存在,就让temp的次数加一
                * 如果不存在,就添加temp,然后value记为一*/
            }
        }
        for (int C:nums3){
            for (int D:nums4){
                temp=C+D;
                /*
                * 
                (A+B)+(C+D)=0
                 (A+B)=0-(C+D)
                 * 看集合中是否存在(A+B)
                 * 如果存在,就累加存储的次数*/
                if (map.containsKey(0-temp)){
                    res+=map.get(0-temp);
                }
            }
        }
        return res;
    }
}

链接:学透哈希表,map使用有技巧!LeetCode:454.四数相加II_哔哩哔哩_bilibili

猜你喜欢

转载自blog.csdn.net/qq_64744030/article/details/130016088