[LeetCode] 4Sum hash表
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
A solution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
- 排序
- 4层遍历
这个时间是O(n^4),这时间不用看也知道超时了。提升的想法是确定3个之后,使用二分法查找提升速度。
- 排序
- 3层遍历
- 二分法查找剩下的target - a-b-c
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
sort(num.begin(),num.end());
vector<vector<int> > ret;
for(int a=;a<num.size();){
for(int b=a+;b<num.size();){
for(int c=b+;c<num.size();){
if(binary_search(num.begin()+c+,num.end(),target-num[a]-num[b]-num[c]))
ret.push_back({num[a],num[b],num[c],target-num[a]-num[b]-num[c]});
c++;
while(c<num.size()&&num[c-]==num[c]) c++;
}
b++;
while(b<num.size()&&num[b-]==num[b]) b++;
}
a++;
while(a<num.size()&&num[a-]==num[a]) a++;
}
return ret;
}
};
这个时间是O(n^3 logn),我写了这个,超时了,那么还需要提升时间,假如有两个数确定了,问题变为从数组中找两数,之和为定值,如果这个查找在有序数列上设左右指针,那么查找时间只需要O(n),这样时间便为 O(n^3)
- 排序
- 从左遍历,每次遍历进入3
- 从右遍历,每次进入4
- 设定左右索引,指向 2、3 还没遍历的数组框左右,判断索引数之和与temp_target,大了右索引左移,小了左索引右移,符合的数放入return。
这个没有写,如果还需要提高时间,那么这样想,因为是4个数之和,可以看成两组数之和,每组两个数,这样如果知道了每两个数之和,问题如上面的转换,这样时间便是O(n^2),不过空间就需要大很多。维持如下的结构:
| -2 | -1 | 0 | 1 | 2 |
| ↓ | ↓ | ↓ | ↓ | ↓ |
| -2,0 | -1,0 | 0,0 | 0,1 | 0,2 |
| -1,-1 | -2,1 | -2,2 | 2,-1 | |
| -1,1 | ||||
维持这样的结构,第一行为组的和,然后指向所有的组合,因为c++ map 是会自动排序的,所以创建 map<int,pari<int,int> > > 这样的一个表便可以了,然后就是剩下判断问题了,如只有 -2 0 2 各一个,但是 -2 2 是可以的,所以需要考虑个数问题。
我用了unorder_map,并没有通过双向收缩来实现,所以判断起来比较麻烦,不过map 在初始化的时候,时间需要logn,所以这样的总体时间是O(n^2logn),这个也是discuss 普遍时间。而使用unorder_map,我的时间是O(n^2 + n*Maxlen(bucket)^2),上图就是Maxlen(bucket)=3,在n较大是较优,注意是+号,毕竟比较难表达,应该会接近O(n^2)。
- 计算两数之和,放入mp 中
- 统计各数的个数,使用map<int,int> cnt 存储
- 遍历mp
- 判断 target- val1 是否在mp 中,否继续遍历,这个时间是O(1)
- 存在的话,如果val1 > val2,continue,为了避免重复
- 遍历bucket1 中的组合
- 遍历bucket2 中的组合,如果 max(group1)<=min(group2)则进入下一步,这是为了避免重复,等号为了 0,0,0,0情况
- 通过cnt 判断数的个数够不够,够的放入return。
- 结束
最终代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <unordered_map>
using namespace std;
/**
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
sort(num.begin(),num.end());
vector<vector<int> > ret;
for(int a=0;a<num.size();){
for(int b=a+1;b<num.size();){
for(int c=b+1;c<num.size();){
if(binary_search(num.begin()+c+1,num.end(),target-num[a]-num[b]-num[c]))
ret.push_back({num[a],num[b],num[c],target-num[a]-num[b]-num[c]});
c++;
while(c<num.size()&&num[c-1]==num[c]) c++;
}
b++;
while(b<num.size()&&num[b-1]==num[b]) b++;
}
a++;
while(a<num.size()&&num[a-1]==num[a]) a++;
}
return ret;
}
};
*/
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
sort(num.begin(),num.end());
vector<vector<int> > ret;
unordered_map<int,vector<pair<int,int> > > mp;
unordered_map<int,int> cnt;
for(unsigned int a=;a<num.size();){
for(unsigned int b=a+;b<num.size();){
mp[num[a]+num[b]].push_back(pair<int,int> {num[a],num[b]});
b++;
while(b<num.size()&&num[b-]==num[b]) b++;
}
a++;
while(a<num.size()&&num[a-]==num[a]) a++;
}
for(unsigned int a = ;a<num.size();a++)
cnt[num[a]]++;
// for(unordered_map<int,int>::iterator it=cnt.begin();it!=cnt.end();it++)
// cout<<it->first<<":"<<it->second<<endl;
// for(unordered_map<int,vector<pair<int,int> > >::iterator it1=mp.begin();it1!=mp.end();it1++){
// cout<<it1->first<<":"<<endl;
// for(int i=0;i<it1->second.size();i++)
// cout<<it1->second[i].first<<" "<<it1->second[i].second<<endl;
// } for(unordered_map<int,vector<pair<int,int> > >::iterator it1=mp.begin();it1!=mp.end();it1++){
// cout<<it1->first<<endl;
unordered_map<int,vector<pair<int,int> > >::iterator it2=mp.find(target - it1->first);
if(it2!=mp.end()){
// cout<<it1->first<<it2->first<<endl;
// cout<<it1->second.size()<<it2->second.size()<<endl;
if(it1->first > it2->first) continue;
for(int i=;i<it1->second.size();i++){
for(int j=;j<it2->second.size();j++){
int a = it1->second[i].first,b = it1->second[i].second,c = it2->second[j].first,d = it2->second[j].second;
if(max(a,b)<=min(c,d)){
bool flag = true;
cnt[a]--;
cnt[b]--;
cnt[c]--;
cnt[d]--;
if(cnt[a]<||cnt[b]<||cnt[c]<||cnt[d]<) flag = false;
cnt[a]++;
cnt[b]++;
cnt[c]++;
cnt[d]++;
// cout<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<flag<<endl;
if(flag){
vector<int> tmp = {a,b,c,d};
sort(tmp.begin(),tmp.end());
ret.push_back(tmp);
}
}
}
}
}
}
return ret;
}
}; int main()
{
vector<int > num = {,,-,,-,};
Solution sol;
vector<vector<int> > ret = sol.fourSum(num,);
for(unsigned int i=;i<ret.size();i++){
copy(ret[i].begin(),ret[i].end(),ostream_iterator<int>(cout," "));
cout<<endl;
}
return ;
}
需要注意的是mp 中的group 是不能重复的,就是如果有 <-1,0>那么便不会有<0,-1>。
[LeetCode] 4Sum hash表的更多相关文章
- LeetCode Continuous Subarray Sum 题解 同余前缀和 Hash表
文章目录 题意 思路 特殊情况k=0 Source Code 1 Source Code 2 题意 给定一个数组和一个整数k,返回是否存在一个长度至少为2的连续子数组的和为k的倍数. 思路 和上一篇博 ...
- 【数据结构】Hash表简介及leetcode两数之和python实现
文章目录 Hash表简介 基本思想 建立步骤 问题 Hash表实现 Hash函数构造 冲突处理方法 leetcode两数之和python实现 题目描述 基于Hash思想的实现 Hash表简介 基本思想 ...
- leetcode的Hot100系列--347. 前 K 个高频元素--hash表+直接选择排序
这个看着应该是使用堆排序,但我图了一个简单,所以就简单hash表加选择排序来做了. 使用结构体: typedef struct node { struct node *pNext; int value ...
- LeetCode longest substring without repeating characters 题解 Hash表
题目 Given a string, find the length of the longest substring without repeating characters. Example 1: ...
- LeetCode subarray-sum-equals-k题解 前缀和+Hash表+枚举——线性做法
文章目录 题意 思路 连续子数组的和sum[i,j] 源码 结果记录 题意 给定一个数组,求连续的子数组的和为k的子数组个数. 思路 连续子数组的和sum[i,j] sum[i,j]=∑k=ijAk( ...
- LeetCode哈希表
1. Two Sum https://leetcode.com/problems/two-sum/description/ 不使用额外空间需要n*n的复杂度 class Solution { publ ...
- python 字典有序无序及查找效率,hash表
刚学python的时候认为字典是无序,通过多次插入,如di = {}, 多次di['testkey']='testvalue' 这样测试来证明无序的.后来接触到了字典查找效率这个东西,查了一下,原来字 ...
- 四种方式带你层层递进解剖算法---hash表不一定适合寻找重复数据
一.题目描述 找出数组中重复的数字 > 在一个长度为 n 的数组 nums 里的所有数字都在 0-n-1 的范围内.数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次. ...
- hash表长度优化证明
hash表冲突的解决方法一般有两个方向: 一个是倾向于空间换时间,使用向量加链表可以最大程度的在节省空间的前提下解决冲突. 另外一个倾向于时间换空间,下面是关于这种思路的一种合适表长度的证明过程: 这 ...
随机推荐
- mysql 查询条件 默认不区分大小写
mysql查询默认是不区分大小写的 如: 1 2 select * from some_table where str=‘abc'; select * from some_table where st ...
- 为什么90%的IT人员都不适合做老大?
什么是格局? 格局就是能够很好的平衡短期利益和长期利益. 过分注重短期利益的人必然会失去长期利益,到头来一定会很普通. 例如:跳槽不断,可能短期薪资会增长,但长期来看后劲可能会不足,未来发展空间会变窄 ...
- 原生js替换jQuery各种方法-中文版
原文https://github.com/nefe/You-D... 原生JS与jQuery操作DOM对比 You Don't Need jQuery 前端发展很快,现代浏览器原生 API 已经足够好 ...
- [转载]win10(64bit)上安装MySQL-python
https://blog.csdn.net/builder_taoge/article/details/78292302 https://blog.csdn.net/qq_26808915/artic ...
- 三分钟明白 Activity工作流 -- java运用
一. 什么是工作流 以请假为例,现在大多数公司的请假流程是这样的 员工打电话(或网聊)向上级提出请假申请——上级口头同意——上级将请假记录下来——月底将请假记录上交公司——公司将请假录入电脑 采用工作 ...
- 从0到n-1中随机等概率输出m个不同的数
//假设输入的n远大于m void knuth(int n, int m) { for (int i = 0; i < n; i++) { if (rand() % (n - i)<m) ...
- A1065 A+B and C (64bit) (20)(20 分)
A1065 A+B and C (64bit) (20)(20 分) Given three integers A, B and C in [-2^63^, 2^63^], you are suppo ...
- C#小知识点积累
1.sealed 修饰符 概念: C#提出了一个密封类(sealed class)的概念,帮助开发人员来解决这一问题. 密封类在声明中使用sealed 修饰符,这样就可以防止该类被其它类继承.如果试图 ...
- HDU 3032 Nim or not Nim?(Multi_SG,打表找规律)
Nim or not Nim? Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)T ...
- 【ELK】ELK安装与配置
一.ELK体系结构 二.系统环境变量 [主机信息] IP 主机名 操作系统版本 10.10.10.102 console CentOS7.5 10.10.10.103 log1 CentOS7.510 ...