LeetCode 454. 4Sum II
来源:互联网 发布:三枪内裤怎么样 知乎 编辑:程序博客网 时间:2024/06/07 02:32
Description:
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
本题思路如下:
题目要求找到满足这样的条件的元组(i,j,k,l):A[i] + B[j] + C[k] + D[l] = 0
可将该条件转化一下,变为:A[i] + B[j] = -C[k] - D[l]
这样转化以后,问题的条件就被转化为了A,B和C,D两部分
接着可以想到使用map来处理这个条件:遍历A和B数组,对于可能的每一个和,像map中进行插入,若已存在该和,则该和对应的次数+1;接着遍历C,D数组,同样,对于每一个可能的和,取该和的负数到map中进行查询,若存在,则找到了使A[i] + B[j] = -C[k] - D[l]条件满足的元组,而元组的个数则是map中该项的值。
代码如下:
class Solution {public: int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { unordered_map<int, int> map; int count = 0; for(auto a: A) { for(auto b: B) { map[a + b]++; } } for(auto c: C) { for(auto d: D) { auto i = map.find(-c - d); if(i != map.end()) { count += i->second; } } } return count; }};
阅读全文
0 0
- 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
- 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] 4Sum II
- Win10操作系统下,Java环境变量的配置和Java入门小程序“hello,world”的编译
- Vue.js 计算属性
- MyBatis入门基础(一) 为什么要用Mybatis
- mybatis入门基础(二)----原始dao的开发和mapper代理开发
- ceph运维常用指令
- LeetCode 454. 4Sum II
- exp/imp三种模式——完全、用户、表
- pygame编写飞机大战(3)-搭建游戏流程
- c++加载驱动文件
- Hive简单部署
- 如何为eclipse安装合适版本的python插件pydev
- 使用eclipse作为python开发工具安装旧版pydev
- 脚本题
- Python使用'input'读取输入文本出现NameError错误