码迷,mamicode.com
首页 > 其他好文 > 详细

3Sum

时间:2015-03-03 23:42:48      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

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)

思路:思路简单,注意重复项的处理

//超时
vector<vector<int> > threeSum(vector<int> &num) {

	vector<vector<int> > ResultVector;
	vector<int>          VectorOne;
	sort(num.begin(), num.end());
	for (int first = 0; first != num.size(); ++first){
		if (num[first] > 0)
			break;
		for (int second = first + 1; second < num.size(); ++second){
			for (int third = second + 1; third < num.size(); ++third){
				int sum = num[first] + num[second] + num[third];
				if (sum == 0)
				{
					
					VectorOne.push_back(num[first]);
					VectorOne.push_back(num[second]);
					VectorOne.push_back(num[third]);
					ResultVector.push_back(VectorOne);
					VectorOne.clear();
				}
			}
		}
	}
	sort(ResultVector.begin(), ResultVector.end(), less<vector<int> >());
	vector<vector<int> >::iterator new_end = unique(ResultVector.begin(), ResultVector.end());
	ResultVector.erase(new_end, ResultVector.end());
	return ResultVector;
}

//AC
vector<vector<int> > threeSum(vector<int> &num) {

	vector<vector<int> > ResultVector;
	vector<int>          VectorOne;
	sort(num.begin(), num.end());
	if (num.size()<3)
		return ResultVector;
	for (int first = 0; first <= num.size() - 3; ++first){
		if (num[first] > 0)
			break;
		if (first != 0  && num[first] == num[first - 1])
			continue;
		int second = first + 1;
		int third = num.size() - 1;
		while (second < third)
		{
			int sum = num[first] + num[second] + num[third];
			if (sum == 0)
			{
				VectorOne.push_back(num[first]);
				VectorOne.push_back(num[second]);
				VectorOne.push_back(num[third]);
				ResultVector.push_back(VectorOne);
				VectorOne.clear();
				second++;
				third--;
				while (second < third&&num[second] == num[second - 1])
					second++;
				while (second < third&&num[third] == num[third + 1])
					third--;
			}
			else if (sum > 0)
				third--;
			else
				second++;
		}
	}

	return ResultVector;
}


 

 

3Sum

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/44044915

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!