Leetcode 15: sum of three numbers

Article directory

Topic 1

Website: 15. The sum of three numbers.

Title Description:

Given a n array nums containing n integers, determine whether there are three elements a, b, c in nums, so that a + b + c = 0? Find out all triples that satisfy the conditions and do not repeat.

Note: The answer should not contain duplicate triples.

Example 1:

For example, given array nums = [-1, 0, 1, 2, -1, -4],

The set of triples satisfying the requirements is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Source: LeetCode
 Link: https://leetcode-cn.com/problems/3sum
 Copyright belongs to the seizure network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, procedure

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

//Sort first, then double pointer method, 160 ms, memory consumption 18MB
vector<vector<int> > threeSum(vector<int>& nums) 
{
	
	vector<vector<int> > res;
	if(nums.size()<3) return res;
	sort(nums.begin(),nums.end());
	for(int i=0;i<nums.size()-2;i++)
	{
		int j=i+1;
		int k=nums.size()-1;
		while (j<k)
		{
			if(nums[i]>0) break;
			if (nums[i]+nums[j]+nums[k]<0)
			{
				j++;
			}
			else if (nums[i]+nums[j]+nums[k]>0)
			{
				k--;
			}
			else
			{
				vector<int> temp;
				temp.push_back(nums[i]);
				temp.push_back(nums[j]);
				temp.push_back(nums[k]);
				res.push_back(temp);
				while(j<nums.size()-2 && nums[j]==nums[j+1]) j++;
				j++;
			}
		}
		while(i<nums.size()-3 && nums[i]==nums[i+1]) i++;
	}
	
	return res;
}

int main()
{
	int a[]={-1,0,1,2,-1,-4};
	vector<int> nums(a,a+sizeof(a)/sizeof(int));
	vector<vector<int>> res;
	res=threeSum(nums);
	for (int i=0;i<res.size();i++)
	{
		for (int j=0;j<res[0].size();j++)
		{
			printf("%d ",res[i][j]);
		}
		printf("\n");
	}

	system("pause");
	return -1;
}

Result:

Keywords: network

Added by xposed on Wed, 02 Oct 2019 21:07:11 +0300