Leetcode:454. 四数相加 II

Leetcode: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

思路

思路1

two sum扩展,直接使用一个哈希表存储A、B列表之和个数,然后遍历满足所有数相交为0的C、D之和,得到最后的结果

代码

代码1

class Solution {
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        if (A == null || A.length == 0 || B == null || B.length == 0 || C == null || C.length == 0 || D == null || D.length == 0){
            return 0;
        }
        Map dictAB = new HashMap<>();
        int result = 0;
        for (int i = 0; i < A.length; i++){
            for(int j = 0; j < B.length; j++){
                int tempSum = A[i] + B[j];
                if (!dictAB.containsKey(tempSum)){
                    dictAB.put(tempSum, 1);
                }else{
                    dictAB.put(A[i] + B[j], dictAB.get(tempSum) + 1);
                }
            }
        }
        
        for(int i = 0; i < C.length; i++){
            for(int j = 0; j < D.length; j++){
                int tempSum = C[i] + D[j];
                if (dictAB.containsKey(-tempSum)){
                    result += dictAB.get(-tempSum);
                }
            }
        }
        return result;
    }
}

复杂度分析

思路1时间复杂度

$O(n^2)$

思路1空间复杂度

$O(n^2)$


文章作者: 小风雷
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小风雷 !
评论
 上一篇
Leetcode:380. 常数时间插入、删除和获取随机元素 Leetcode:380. 常数时间插入、删除和获取随机元素
Leetcode: 380. 常数时间插入、删除和获取随机元素题目描述设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。 insert(val):当元素 val 不存在时,向集合中插入该项。 remove(val):元
2020-04-09
下一篇 
Leetcode:171. Excel表列序号 Leetcode:171. Excel表列序号
Leetcode: 171. Excel表列序号题目描述给定一个Excel表格中的列名称,返回其相应的列序号。 例如,A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB
2020-04-08
  目录