LeetCode:3Sum

思路:首先对数组进行排序,因为只有排序之后才可以对三个数的和计算进行截断控制,省去C(3,n)中待解空间的很多不是解的组合。
另外排序之后可以对重复的三元组进行很简单的处理,也可以加速解的寻找。

	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)


<pre name="code" class="cpp">class Solution {
	public:
		vector<vector<int> > threeSum(vector<int> &num) {
			vector<vector<int>> result;
			result.clear();
			if (num.size() < 3)
			{
				return result;
			}

			sort(num.begin(), num.end());
			for (size_t i = 0; i < num.size() - 2; i++)
			{
				if (num[i]>0) break;
				for (size_t j = i + 1; j < num.size() - 1; j++)
				{
					if (num[i] + num[j] > 0) break;
					int tar = 0 - (num[i] + num[j]);
					for (size_t k = j + 1; k < num.size(); k++)
					{
						if (num[k] > tar) break;
						if (tar == num[k])
						{
							vector<int> tem;
							tem.push_back(num[i]);
							tem.push_back(num[j]);
							tem.push_back(num[k]);
							result.push_back(tem);
							while (num[i] == num[i + 1]) ++i;//排除重复的三元组,没有这两句的话会超时
							while (num[j] == num[j + 1]) ++j;
							break;
						}
						
					}
				}
			}

			return result;
		}
		void test()
		{
			vector<int> data = { 7, -1, 14, -12, -8, 7, 2, -15, 8, 8, -8, -14, -4, -5, 7, 9, 11, -4, -15, -6, 1, -14, 4, 3, 10, -5, 2, 1, 6, 11, 2, -2, -5, -7, -6, 2, -15, 11, -6, 8, -4, 2, 1, -1, 4, -6, -15, 1, 5, -15, 10, 14, 9, -8, -6, 4, -6, 11, 12, -15, 7, -1, -9, 9, -1, 0, -4, -1, -12, -2, 14, -9, 7, 0, -3, -4, 1, -2, 12, 14, -10, 0, 5, 14, -1, 14, 3, 8, 10, -8, 8, -5, -2, 6, -11, 12, 13, -7, -12, 8, 6, -13, 14, -2, -5, -11, 1, 3, -6 };

			for each (int var in data)
			{
				cout << var << ",";
			}
			cout << "\b " << endl;

			vector<vector<int> > res = threeSum(data);

			for each (vector<int> var in res)
			{
				for each(int t in var)
					cout << t << ",";
				cout << "\b " << endl;
			}
		}
	};


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值