数组中三数之和

题目描述

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

测试用例

示例 1:

输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:

输入:nums = []
输出:[]
示例 3:

输入:nums = [0]
输出:[]

代码

#include <iostream>
#include <vector>

using namespace std;

int main()
{
	vector<int> nums={ -1,0,1,2,-1,-4 };
	int n = nums.size();

	sort(nums.begin(), nums.end());

	int s = 0;//用来计算三个元素的和是否为0	
	vector<vector<int>> threeSum(0, vector<int>(3));
	
	if (n < 3)
	{
		cout << "Datad Error" << endl;
	}
	else if (n == 3)
	{
		s = nums[0] + nums[1] + nums[2];
		if (s == 0)
		{
			threeSum.push_back({ nums[0], nums[1], nums[2] });
		}
	}
	else
	{
		//枚举a,a=n-1,n-2时,b,c已经没有元素了
		for (int a = 0; a < n - 2; a++)
		{
			if (nums[a] > 0)//数组中最小的元素大于0,其后的所有元素之和肯定都大于0
			{
				break;
			}
			else if (a > 0 && nums[a] == nums[a - 1])
			{
				continue;
			}
			else
			{
				//双指针法
				for (int b = a + 1, c = n - 1; b < c;)
				{
					s = nums[a] + nums[b] + nums[c];
					if (s < 0)
					{
						while (b < c && nums[b] == nums[b++]);
					}
					else if (s > 0)
					{
						while (b < c && nums[c] == nums[c--]);
					}
					else
					{
						threeSum.push_back({ nums[a], nums[b], nums[c] });
						while (b < c && nums[b] == nums[b++]);
						while (b < c && nums[c] == nums[c--]);
					}
				}
			}
		}

	}

	for (int i = 0; i < threeSum.size(); i++)
	{
		for (int j = 0; j < threeSum[0].size(); j++)
		{
			cout << threeSum[i][j] << "   ";
		}
		cout << endl;
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值