4Sum
2015-08-12 10:07
281 查看
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.
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
int ln=num.size();
vector<vector<int>> avec;
if(ln<4)
return avec;
vector<int>::iterator iter=num.begin();
sort(num.begin(), num.end());
int t,l,h;
for(int a=0;a<ln-3;a++){
for(int b=a+1;b<ln-2;b++){
l=b+1;
h=num.size()-1;
vector<int> res(4);
t=target-num[a]-num[b];
while(l<h){
int s=num[l]+num[h];
if(s<t){
l++;
continue;
}
if(s>t){
h--;
continue;
}
if(s==t){
res[0]=num[a];
res[1]=num[b];
res[2]=num[l];
res[3]=num[h];
avec.push_back(res);
//res.clear();
l++;
h--;
}
}
}
}
vector<vector<int> > ans;
for(int i = 0; i < avec.size(); ++i)
if(find(ans.begin(), ans.end(), avec[i]) == ans.end()) //find函数应用
ans.push_back(avec[i]);
return ans;
}
};
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)
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
int ln=num.size();
vector<vector<int>> avec;
if(ln<4)
return avec;
vector<int>::iterator iter=num.begin();
sort(num.begin(), num.end());
int t,l,h;
for(int a=0;a<ln-3;a++){
for(int b=a+1;b<ln-2;b++){
l=b+1;
h=num.size()-1;
vector<int> res(4);
t=target-num[a]-num[b];
while(l<h){
int s=num[l]+num[h];
if(s<t){
l++;
continue;
}
if(s>t){
h--;
continue;
}
if(s==t){
res[0]=num[a];
res[1]=num[b];
res[2]=num[l];
res[3]=num[h];
avec.push_back(res);
//res.clear();
l++;
h--;
}
}
}
}
vector<vector<int> > ans;
for(int i = 0; i < avec.size(); ++i)
if(find(ans.begin(), ans.end(), avec[i]) == ans.end()) //find函数应用
ans.push_back(avec[i]);
return ans;
}
};
相关文章推荐
- 如何获取经纬度之间两点间真实距离(适用于GoogleMap,BaiduMap,Amap等)
- Hibernate 缓存机制
- 字符串中第一次只出现一次的字符(×60内推笔试)
- AppStore审核问题
- Why Coding Like this -------Optional揭秘 自己写一个可选类型类
- 我的实习作品:基于GeoHey地图的学区房应用
- HDU 3226 背包
- Apache+Tomcat集群配置
- HDU 5375 DP
- redis设计与实现
- setsockopt用法详解
- boost------ref的使用(Boost程序库完全开发指南)读书笔记
- NZND壳-设计
- C# 创建自定义集合编辑器/自定义集合属性
- 中国互联网金融协会挂牌在即
- bzoj2821: 作诗(Poetize)
- constants 常量值的使用
- Redis底层数据结构总结
- stdafx.h的作用体会
- 开源中国源码学习(七)——DrawerLayout使用