zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 454 四数相加 II

    454. 四数相加 II

    给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。

    为了使问题简单化,所有的 A, B, C, D 具有相同的长度 N,且 0 ≤ N ≤ 500 。所有整数的范围在 -228 到 228 - 1 之间,最终结果不会超过 231 - 1 。

    例如:

    输入:
    A = [ 1, 2]
    B = [-2,-1]
    C = [-1, 2]
    D = [ 0, 2]

    输出:
    2

    解释:
    两个元组如下:

    1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
    2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
    class Solution { 
        public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
            Map<Integer ,Integer> mapAB =new HashMap<>();
            int res =0;
    
            for(int i =0 ; i<A.length ;i++){
                for(int j =0 ; j<B.length ;j++){
                    int key =A[i]+B[j];
                    if(mapAB.containsKey(key))
                        mapAB.put(key,mapAB.get(key)+1);
                    else mapAB.put(key,1);
                }
            }
    
            for(int i =0 ; i<C.length ;i++){
                for(int j =0 ; j<D.length ;j++){
                    int key =C[i]+D[j];
                    if(mapAB.containsKey(0-key)){
                        res += mapAB.get(0-key);
                    }
                }
            }
            return res;
    
        }
    }
    
  • 相关阅读:
    ubuntu
    eclipse 链接 hadoop
    javaweb访问hdfs的一些错误
    eclipse
    ubuntu
    ubuntu
    ubuntu
    ubuntu 安装 mysql
    光源选择
    C#脱离Halcon编程开发环境使用方法
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13075656.html
Copyright © 2011-2022 走看看