LeetCode 15.3Sum

题目:

Given an array S of n integers, are there elements abc 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)
分析与解答:

从简单的情况开始考虑,比如只需要计算两个数的和是不是等于0,复杂度O(n),方法参见two sum。所以对于3sum一开始我也尝试寻找线性时间内的解,后来发现难度较大。退而求其次,因为结果要求是有序的,那就先排序吧,但即便是有序之后依然需要O(n^2)的时间。所以此题并未找到更简单的解法,在wiki上的方法是和我一样的。三个指针,固定一个,然后另两个一头一尾进行遍历。

需要注意的是:题目要求不能有重复结果。所以要想办法剔除相同的数字。三个指针分别指向三个数,当每个指针在自己的合法范围内碰到相同的数字,就直接跳过即可。


class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
	vector<vector<int> > result;
	if (num.empty() || num.size() < 3)
		return result;
	sort(num.begin(), num.end()); //排个序先
	int head = 0, end = 0;
	for (int i = 0; i < num.size() - 2; i++) {
		while (i && (num[i] == num[i - 1])) {
			i++;
		}
		head = i + 1, end = num.size() - 1;
		while (head < end) {
			if (num[i] + num[head] + num[end] == 0) {
				int t[3] = { num[i], num[head], num[end] };
				vector<int> temp(t, t + 3);
				result.push_back(temp);
				while (head < end && (temp[1] == num[head]))
					head++;
				while (head < end && (temp[2] == num[end]))
					end--;
			} else if (num[i] + num[head] + num[end] > 0)
				end--;
			else
				head++;
		}
	}
	return result;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值