Given an array S of n integers, are there elements a, b, c 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;
}