您的位置:首页 > 其它

【LeetCode】3Sum

2014-04-01 14:30 218 查看

参考:

http://blog.csdn.net/xshalk/article/details/8148422

题目描述


3Sum

 

Given an array S of n integers, are there elements a, b, c in S such that a + b + c =
0? Find all unique triplets in the array which gives the sum of zero.
Note:

Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.

For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:
(-1, 0, 1)
(-1, -1, 2)


题目分析

题目大意:给定一个数组,存在三个数a,b,c符合a+b+c=0。列出所有可能性。
输出要求,abc必须符合a ≤ b ≤ c
思路:
这个可以转换为tow sum问题。逐个遍历数组,取出一个元素a,然后利用twosum问题找出两个相加等于b+c=-a。

对于2sum问题
需要先对数据进行排序。

把数组进行排序,然后首尾各定义一个指针head,tail,
如果target>(num[head]+num[tail]) tail--;
如果target<(num[head]+num[tail]) head++;

如果排序的复杂度为nlogn,那个3sum复杂度为n^2logn

代码示例

/*
编译环境CFree 5.0
博客地址:http://blog.csdn.net/Snowwolf_Yang
*/
#include
#include
using namespace std;

/*
vector > 后一个>前需要加一个空格
*/

class Solution {
public:
vector > threeSum(vector &num) {
vector > ret;
ret.clear();
sort(num.begin(),num.end());
for(int i=0; i!=num.size();i++){
if(i > 0 && num[i]==num[i-1])		//和前一个相同表示该子问题已经解决
continue;
int j,k;
j=i+1;
k=num.size()-1;
while(ji+1&&num[j]==num[j-1]){ 	//和前一个相同表示该子问题已经解决
j++;
continue;
}
if(k0){
k--;
}else if(sum<0){
j++;
}else{
vector tmp;
tmp.push_back(num[i]);
tmp.push_back(num[j]);
tmp.push_back(num[k]);
ret.push_back(tmp);
j++;
}
}
}
return ret;

}
};
void test0()
{
int arr[] = {0,-1,2,3,-4,5,6,-7,8,9};
vector numbers (arr, arr + sizeof(arr) / sizeof(int) );
Solution so;
vector< vector > out = so.threeSum(numbers);
int i = 0,j = 0, flag = 1;
for(i = 0;i


推荐学习C++的资料

C++标准函数库
http://download.csdn.net/detail/chinasnowwolf/7108919

在线C++API查询
http://www.cplusplus.com/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode sum 3sum