4Sum
2015-10-29 21:13
288 查看
题目: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)
思路:
先是保存前面数字两两之和,接下来,和之前一样,上来就是两个循环,如果有重复的,continue。后面就是看是不是有target-num[i]-num[j],有的话,则开始最重要的程序了,首先,看hash里面的第一个数值是否大于刚刚的j,因为我们是从后往前的。不可能小于。
还有就是要区分是否是第一次放进去,如果第二次放进去的话,那么,就需要考虑 res中倒数第二个数,不能够和hash表第一个数相同。
因为此时,第一个,第二个数都是相同的,第三个数相同,那么第四个一定相同。
代码:
class Solution {public:
//http://www.cnblogs.com/tenosdoit/p/3649607.html 非常好的一篇博客
vector<vector<int> > fourSum(vector<int> &num, int target) {
int n=num.size();
vector<vector<int> > res;
unordered_map<int,vector<pair<int,int> >>pairs;
sort(num.begin(),num.end());
//先保存 前面两数的和
for(int i=0;i<=n-2;i++){
for(int j=i+1;j<=n-1;j++){
pairs[num[i]+num[j]].push_back(make_pair(i,j));
}
}
for(int i=0;i<=n-4;i++){
if(i>0&&num[i]==num[i-1]) continue;//避免重复元素
for(int j=i+1;j<=n-3;j++){
if(j>i+1&&num[j]==num[j-1]) continue;
if(pairs.find(target-num[i]-num[j])!=pairs.end()){
bool isFirstPush=true;
vector< pair<int,int> > sum2=pairs[target-num[i]-num[j]];
for(int k=0;k<sum2.size();k++){
if(sum2[k].first<=j) continue;//新找出来的数组索引值一定要大于之前的两个索引值,i,j
if(isFirstPush||(res.back())[2]!=num[sum2[k].first]){
res.push_back(vector<int>{num[i],num[j],num[sum2[k].first],num[sum2[k].second]});
isFirstPush=false;
//这里较难理解,因为我第一次可以有重复 1 2 2 3,但是第二次就不行
//如果有1 2 2,第四个数字一定是3,就一定会重复
}
}
}
}
}
return res;
}
};
相关文章推荐
- CentOS系统下xinetd启动问题
- IOS开发笔记27-应用管理之MVC模式
- Xen的安装、编译和使用(二)
- R语言学习之包的加载和日期包的使用
- 矩阵乘法+快速幂求斐波那契
- 基于saltstack svn的一个发布系统
- 二分图的最大匹配
- hdoj--1251--统计难题(字典树)
- 挖掘频繁模、关联和相关性(2)
- android studio使用jcenter上的开源库
- SOM-TL28335核心板规格书
- [原创] Cygwin完全下载指南(上)-正常下载篇
- hdoj--1251--统计难题(字典树)
- Nginx缓存配置及nginx ngx_cache_purge模块的使用
- 递归算法小例子
- ios应用数据存储方式(归档)
- 初识onMeasure()——解决ScrollView内嵌ListView滑动冲突
- 《软件需求十步走》阅读笔记三
- 使用WPR和WPA分析线程等待(分析锁的影响)
- java基础语法