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: 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 =0 的a,b,c,3个元素

思路:暴力破解,其实我们都想到,但是这样面临着两个问题,首先是时间复杂度的问题,然后3个for循环还可能会导致重复选取的问题。

            解题思路是:可以把它转化为 a+b =-c的问题。选取数组的其中一个数,对其添加负号。看是否满足存在两个数相加刚好等于它的负数。

class Solution {
public:
	vector<vector<int>> threeSum(vector<int> &nums) {
		vector<vector<int>> res;
		sort(nums.begin(), nums.end()); //先对其进行排序,缩短寻找的时间复杂度。
		for (int i = 0; i < nums.size(); i++) {
			int target = -nums[i];
			int front = i + 1;
			int back = nums.size() - 1;
			//如果target小于0,意味着nums[i]为正,而nums[front]和nums[back]都会大于它,所以不存在的
			if (target < 0) {
				break;
			}

			while (front < back) {
				int sum = nums[front] + nums[back];
				if (sum < target) front++;
				else if (sum > target) back--;
				else {
					vector<int> arry(3, 0);
					arry[0] = nums[i];
					arry[1] = nums[front];
					arry[2] = nums[back];
					res.push_back(arry);

					while (front < back &&nums[front] == arry[1]) front++;
					while (front < back &&nums[back] == arry[2]) back--;

				}
			}
			//筛除相等的数
			while (i + 1 < nums.size() && nums[i + 1] == nums[i])
				i++;
		}
		return res;
	}
};

当然还有KSum问题,我们稍后再讨论

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值