zoukankan      html  css  js  c++  java
  • 力扣454题(四数之和)

    454、四数之和

    基本思想:

    HashMap

    具体实现:

    1.定义一个HashMap,key放a和b两数之和,value放a和b两数之和出现的次数

    2.遍历num1和nums2数组,统计两个数组元素之和出现的次数,放到map中

    3.定义int变量res,用来统计a+b+c+d = 0出现的次数

    4.在遍历nums3和nums4数组,找到如果0 - (c + d)在map中出现过的话,

    就用count吧map中key对应的value(也就是出现次数)统计出来

    5.最后返回统计值res就可以了

    代码:

    class Solution {
        public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
            Map<Integer,Integer> map = new HashMap<>();
            int temp;
            int res = 0;
            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);
                    }
                }
            }
    
            for (int i : nums3){
                for (int j : nums4){
                    temp = i + j;
                    if (map.containsKey(0 - temp)) {
                        res += map.get(0 - temp);
                    }
                }
            }
    
            return res;
        }
    }
  • 相关阅读:
    EFCore
    PS-邮件发送异常信息
    python-Django
    Autofac
    swagger
    查看哪个程序占用了端口
    SQL SERVER-系统数据库还原
    破解root密码
    WebApi路由
    async,await.task
  • 原文地址:https://www.cnblogs.com/zhaojiayu/p/15496522.html
Copyright © 2011-2022 走看看