leetcode 454. 4Sum II 使用Map降低运算复杂的
来源:互联网 发布:ping ip加端口怎么写 编辑:程序博客网 时间:2024/06/16 12:45
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:
2
Explanation:
The two tuples are:
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
题意很几简单,应该使用map来做标记来降低复杂度,嗯嗯,很不错的题,直接遍历肯定超时。
建议和这一道题leetcode 18. 4Sum KSum的解决办法 一起学习
代码如下:
#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <cmath>using namespace std;class Solution {public: int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { int target = 0; map<int, int> abSum; for (int a : A) { for (int b : B) { abSum[a + b]++; } } int count = 0; for (int c : C) { for (int d : D) { if (abSum.find(target - c - d) != abSum.end()) count += abSum[target - c - d]; } } return count; }};
阅读全文
0 0
- leetcode 454. 4Sum II 使用Map降低运算复杂的
- 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
- spring-boot-mybatis-cache-thymeleaf学习
- Week03_day05 集合(下)
- Ubuntu系统环境变量详解
- mysql5.7官网直译数据结构优化--数据大小优化
- uva1583
- leetcode 454. 4Sum II 使用Map降低运算复杂的
- android开发实现下载网页图片到本地并显示
- recovery&linux系统升级数据更新分析总结
- 算法基本概念
- 图--分类及存储结构(数据结构)
- Linux基本命令的使用及目录权限问题
- Object 类中的 equals方法
- 阿里面试问题(转牛客网上分享的题目)
- dom4j遍历xml文件