Hash Table -- Leetcode problem454. 4Sum II
来源:互联网 发布:淘宝旧版本5.7.0下载 编辑:程序博客网 时间:2024/05/21 01:54
- 描述: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 -2^28 to 2^28 - 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:
- (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
- (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
- 分析:这是一道寻找四个数组中有多少个元素只和为0的题目,首先,暴力解法(4层循环)是行不通的,因为数组元素较多,会浪费很多时间。
- 思路一:直接用map解题,先判断两个数组只和,然后用第三个和第四个数组只和的相反数在前两个和之中寻找,如果找到,给计数器加上匹配的数值。 (579 ms)
class Solution {public: int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { map<int, int> my_map; int flag = 0; for (int i = 0; i < A.size(); i++) { for (int j = 0; j < B.size(); j++) { my_map[A[i]+B[j]]++; } } for (int i = 0; i < C.size(); i++) { for (int j = 0; j < D.size(); j++) { if (my_map.find(-(C[i] + D[j])) != my_map.end()) { flag += my_map[-(C[i] + D[j])]; } } } return flag;}};
- 思路二:用unordered_map作为容器可以使时间减少一倍。(242 ms)
class Solution {public: int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { unordered_map<int, int> my_map; int flag = 0; for (int i = 0; i < A.size(); i++) { for (int j = 0; j < B.size(); j++) { my_map[A[i]+B[j]]++; } } for (int i = 0; i < C.size(); i++) { for (int j = 0; j < D.size(); j++) { if (my_map.find(-(C[i] + D[j])) != my_map.end()) { flag += my_map[-(C[i] + D[j])]; } } } return flag;}};
阅读全文
0 0
- Hash Table -- Leetcode problem454. 4Sum II
- Leetcode 454 - 4Sum II(hash)
- LeetCode[Hash Table]: Two Sum
- [LeetCode] 4Sum II
- Hash Table -- Leetcode problem350. Intersection of Two Arrays II
- LeetCode 454. 4Sum II
- Leetcode-454. 4Sum II
- Leetcode 之 4Sum II
- LeetCode 454 4Sum II
- LeetCode 454. 4Sum II
- Leetcode-454. 4Sum II
- 【LeetCode】 454. 4Sum II
- [leetcode]454. 4Sum II
- 【Leetcode】454. 4Sum II
- Leetcode 454. 4Sum II
- LeetCode 454. 4Sum II
- [LeetCode] 454. 4Sum II
- leetcode 454. 4Sum II
- 极乐技术周报(第二十七期)
- DPDK 设备命令行添加
- 径向基函数(RBF)神经网络
- SAP HANA Express Edition (HXE)-虚拟机模板安装使用步骤
- 卷积神经网络CNN简介
- Hash Table -- Leetcode problem454. 4Sum II
- 数据流图错误汇总
- Java线程池的分析和使用
- Linux 基础命令(第二天)
- expdp/impdp导入导出数据
- 【C#】 .NET Reflector 安装与破解
- 0-1背包
- ansible之并发运行
- Tensorflow学习-工具相关