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, abc)
  • 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)


题目解析:

(1)我们将输入的数组进行排序。

(2)从第一开始进行遍历,那么需要后面的元素加起来是等于temp = -A[0],

因为后面的元素已经排好序了,如果后面元素的第一个与最后一个相加大于temp,那么我们应该把大的值调小,因此最后的end 需要减一。

同理当相加小于temp的时候,如果等于说明找到了。

(3)去除重复有两个地方。

外循环的时候,如果这个元素与前面的元素不同则处理,相同则不处理,进1。

内循环的时候也是相同的。

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

vector<vector<int> > threeSum(vector<int> &num) {
	sort(num.begin(),num.end());
	int len = num.size();
	vector<vector<int>> triplets;
	if(len < 3)
		return triplets;

	for(int i=0;i<len-2;i++)
	{
		while(i-1>=0 && i<len-2 && num.at(i-1) == num.at(i))
			i++;

		int remain = 0 - num.at(i);
		int begin = i + 1;
		int end = len -1;

		while(begin < end)
		{
			int restemp = num.at(begin)+num.at(end);
			if(restemp > remain)
				end--;
			if(restemp < remain)
				begin++;
			if(restemp == remain)
			{
				vector<int> temp;
				temp.push_back(num.at(i));
				temp.push_back(num.at(begin));
				temp.push_back(num.at(end));
				triplets.push_back(temp);
				while(begin < end && num.at(begin+1) == num.at(begin))
					begin = begin + 1;
				while(begin < end && num.at(end-1) == num.at(end))
					end = end - 1;
				begin++;
			}
		}
	}
	return triplets;
}

void printArray(vector<vector<int> > &result)
{
	int len = result.size();
	for(int i=0;i<len;i++)
	{
		vector<int> temp = result.at(i);
		cout << "[" ;
		for(int j=0;j<(int)temp.size();j++)
		{
			cout << temp.at(j) << " ";
		}
		cout << "]" << endl;
	}
}

int main(void)
{
	vector<int> num;
	num.push_back(-4);
	num.push_back(-2);
	num.push_back(1);
	num.push_back(-5);
	num.push_back(-4);
	num.push_back(-4);
	num.push_back(4);
	num.push_back(-2);
	num.push_back(0);
	num.push_back(4);
	num.push_back(0);
	num.push_back(-2);
	num.push_back(3);
	num.push_back(1);
	num.push_back(-5);
	num.push_back(0);

	vector<vector<int> > triplets = threeSum(num);

	printArray(triplets);
	system("pause");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值