[LeetCode-Medium Question] 15. Sum of three numbers

Article directory

topic

Insert image description here

Method 1: Hash table

Simplify the sum of four numbers into the sum of two numbers with the help of a hash table

Insert image description here

class Solution {
    
    
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
    
    
        int res = 0;  //结果集数量
        Map<Integer,Integer> map = new HashMap<>();//记录前两个数组的和以及出现次数
        for(int i : nums1)
            for(int j : nums2){
    
    
             if(!map.containsKey(i+j)) map.put(i+j,1);
             else map.put(i+j,map.get(i+j)+1);
        }

        //遍历后面两个数组取出各自的结果  然后再依次去加上map的key是否等于0,如果是 则将对应的次数加入结果集
        //因为这里已经把四数相加  简化成了两数相加了,并且相加结果要为0    那么他们之间要相加等于0   那么肯定是互为相反数的
         for(int i : nums3)
            for(int j : nums4){
    
    
                int temp = (i+j)*-1;//取相反数
                if(map.containsKey(temp)) res+=map.get(temp);//得到相加为0 的数的次数
            }
            return res;
    }
}

Guess you like

Origin blog.csdn.net/weixin_45618869/article/details/132872891