3Sum

本文探讨了如何寻找数组中三个数相加等于零的所有唯一组合,并提供了一种高效的解决方案。通过对数组进行排序并采用双指针技巧,有效避免了重复结果的产生。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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]
]
解题思路:

首先对数组进行升序排序,然后遍历数组中的元素,固定当前遍历到的元素为第一个数,另外两个数一个从固定的数的后面一个开始,一个从数组的最后一个数开始,移动后两个数找到合适的三元组。


AC代码如下:

class Solution{
public:
	vector<vector<int>> threeSum(vector<int>& nums){
		vector<vector<int>> ans;
		if (nums.size() < 3) return ans;
		sort(nums.begin(), nums.end());
		int n = nums.size();
		for (int i = 0; i < n; ++i){
			if (i>0 && nums[i] == nums[i - 1]) continue; //跳过重复的元素,避免结果中出现相同的三元组
			int j = i + 1, k = n - 1;
			while (j < k){
				int sum = nums[i] + nums[j] + nums[k];
				if (sum == 0){
					vector<int> tmp = { nums[i], nums[j], nums[k] };
					ans.push_back(tmp);
					while (++j < k && nums[j] == nums[j - 1]); //跳过重复的元素,避免结果中出现相同的三元组
					while (j < --k && nums[k] == nums[k + 1]); //跳过重复的元素,避免结果中出现相同的三元组
				}
				else if(sum>0){
					--k;
				}
				else{//sum<0
					++j;
				}
			}
		}
		return ans;
	}
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值