计算三个数合为0

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.

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

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

很久没有接触这类算法,光快速排序就好久没写了 ,码起来有点费力,调了好久

遇到的问题 :

1 快速排序 边界条件设置

2  采用两头向内搜索的方法查找 两数和为当前数的负数,对已经计入过的数要跳过 ,循环控制条件没有设置好。

// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <vector>
using namespace std;
int partition(vector<int>& numbers, int l, int h)
{
	int i = 0;
	if (l >= h)
		return l;
	int com = numbers[l];
	while (l<h)
	{
		while (h>l&&numbers[h] >= com)
		{
			h--;
		
		}
		if(h>l)
			numbers[l++] = numbers[h];
		while (l<h&&numbers[l] <= com)
		{
			l++;
			
		}
		if (l<h)
			numbers[h--] = numbers[l];
	}
	numbers[l] = com;
	return l;
}
void quicksort(vector<int>&numbers, int l, int h)
{
	if (l >= h)
	{
		return;
	}
	int par = partition(numbers, l, h);
	quicksort(numbers, l, par - 1);
	quicksort(numbers, par + 1, h);
}
vector<vector<int>> threeSum(vector<int>& nums) {
	vector<int> myvector = nums;
	vector<vector<int>> ret;
	int len = myvector.size();
	if (len<3)
		return ret;
	quicksort(myvector, 0, len - 1);
	if (myvector[0] > 0)
		return ret;
	for (int j = 0; j<len - 2; j++)
	{
		int value = 0 - myvector[j];
		
		int l = j + 1;
		int h = len - 1;
		if (j > 0 && myvector[j] == myvector[j - 1])
			continue;

		while (l<h)
		{
		
			if (myvector[l] + myvector[h] == value)
			{
				vector<int> node;
				node.push_back(myvector[j]);
				node.push_back(myvector[l]);
				node.push_back(myvector[h]);
				ret.push_back(node);
				l++;
				h--;
				while (l<h&&myvector[l] == myvector[l -1]) //比对方向反了
					l++;
				while (h>l&&myvector[h] == myvector[h +1]) //比对方向反了
					h--;
			}
			else if (myvector[l] + myvector[h]<value)
			{
				l++;
			}
			else
			{
				h--;
			}
		}
	}
	return ret;
}
int main()
{
	vector<int> nums = { -4, -2, 1, -5, -4, -4, 4, -2, 0, 4, 0, -2, 3, 1, -5, 0 };
	vector<vector<int>> ret;
	ret = threeSum(nums);
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值