博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 4Sum II 四数之和之二
阅读量:4308 次
发布时间:2019-06-06

本文共 2063 字,大约阅读时间需要 6 分钟。

 

Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

Example:

Input:A = [ 1, 2]B = [-2,-1]C = [-1, 2]D = [ 0, 2]Output:2Explanation:The two tuples are:1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 02. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

 

这道题是之前那道的延伸,让我们在四个数组中各取一个数字,使其和为0。那么坠傻的方法就是遍历所有的情况,时间复杂度为O(n4)。但是我们想想既然那道都能将时间复杂度缩小一倍,那么这道题我们使用哈希表是否也能将时间复杂度降到O(n2)呢?答案是肯定的,我们如果把A和B的两两之和都求出来,在哈希表中建立两数之和跟其出现次数之间的映射,那么我们再遍历C和D中任意两个数之和,我们只要看哈希表存不存在这两数之和的相反数就行了,参见代码如下:

 

解法一:

class Solution {public:    int fourSumCount(vector
& A, vector
& B, vector
& C, vector
& D) { int res = 0; unordered_map
m; for (int i = 0; i < A.size(); ++i) { for (int j = 0; j < B.size(); ++j) { ++m[A[i] + B[j]]; } } for (int i = 0; i < C.size(); ++i) { for (int j = 0; j < D.size(); ++j) { int target = -1 * (C[i] + D[j]); res += m[target]; } } return res; }};

 

这种方法用了两个哈希表分别记录AB和CB的两两之和出现次数,然后遍历其中一个哈希表,并在另一个哈希表中找和的相反数出现的次数,参见代码如下:

 

解法二:

class Solution {public:    int fourSumCount(vector
& A, vector
& B, vector
& C, vector
& D) { int res = 0, n = A.size(); unordered_map
m1, m2; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { ++m1[A[i] + B[j]]; ++m2[C[i] + D[j]]; } } for (auto a : m1) res += a.second * m2[-a.first]; return res; }};

 

类似题目:

 

参考资料:

 

转载于:https://www.cnblogs.com/grandyang/p/6073317.html

你可能感兴趣的文章
QT分页控件,开源,供大家使用
查看>>
005.LVM删除
查看>>
Hibernate 简介(百度)
查看>>
深入理解 KVC\KVO 实现机制 — KVC
查看>>
Android develop 国际化
查看>>
快速求幂算法
查看>>
Freemarker模板引擎
查看>>
jQuery:表格的奇偶行变色,jquery实例之表格隔一行
查看>>
(Object-C)学习笔记(一)--开发环境配置和与c语言的区别
查看>>
hdu 3549 Flow Problem(最大流模板)
查看>>
编译器错误 CS1026
查看>>
centos安装coreseek
查看>>
gitlab应用
查看>>
$Django importlib与dir知识,手写配置文件, 配置查找顺序 drf分页器&drf版本控制
查看>>
对layoutInflater的理解
查看>>
网络流之最大流问题
查看>>
【自己给自己题目做】之一:椭圆可点击区域
查看>>
Uva 1625 - Color Length(DP)
查看>>
练习2-1 Programming in C is fun!
查看>>
isset函数
查看>>