题目描述
给出一个有n个元素的数组S,S中是否有元素a,b,c满足a+b+c=0?找出数组S中所有满足条件的三元组。
注意:
三元组(a、b、c)中的元素必须按非降序排列。(即a≤b≤c)
解集中不能包含重复的三元组。
例如,给定的数组 S = {-10 0 10 20 -10 -40},解集为(-10, 0, 10) (-10, -10, 20)
以下C++语言实现
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
//--测试用例--
#define ARRAY_LEN 25
#define ARRAY_VALUE { -10,0,10,20,-10,\
-40,30,-50,-5,25,\
15,35,-15,16,50,\
20,25,5,0,0,\
-20,0,15, 5,4\
}
int main(void)
{
int test_array[ARRAY_LEN]=ARRAY_VALUE;
vector<int> my_array(test_array,test_array+ARRAY_LEN);
//排序,以加速查找三元组
sort(my_array.begin(),my_array.end());
for( vector<int>::iterator ij=my_array.begin();ij<my_array.end();ij++)
{ cout<<*ij<<" "; }
cout<<"\n-----------------------------------------------------"<<endl;
// vector<int>::iterator end_unique=unique(my_array.begin(),my_array.end());
// my_array.erase(end_unique,my_array.end());
// for(ii=my_array.begin();ii<my_array.end();ii++)
// { cout<<*ii<<" "; }
//迭代器:ii,jj,kk, zzz
vector<int>::iterator ii=my_array.begin();
vector<int>::iterator jj=ii;
vector<int>::iterator kk=ii;
vector<int>::iterator zzz=my_array.end();
while(ii<(zzz-2))
{
jj =ii+1;
//后续必大于0,直接退出本轮迭代
if(*ii> 0 )
{ break; }
while(jj<(zzz-1))
{
kk=jj+1;
int temp = (*ii)+(*jj);
//相同元素时,避免重复找出
if(*jj==*kk)
{ jj++;
if( (*kk)+temp == 0)
{
cout<<"[ "<<*ii<<" "<<*jj<<" "<<*kk<<" ]"<<endl;
}
if(*ii == *jj)
{ ii++; jj++; }
continue;
}
//后续必大于0,直接退出本轮迭代
if( temp > 0 )
{ break; }
while(kk<zzz)
{ int temp_p = temp+(*kk);
if(temp_p == 0 )
{
cout<<"[ "<<*ii<<" "<<*jj<<" "<<*kk<<" ]"<<endl;
break;
}
else if( temp_p > 0)
{ break; }
else
{ kk++; }
}
//相同元素时,避免重复找出
if(*ii == *jj)
{ ii++; }
jj++;
}
ii++;
}**加粗样式**
}
测试输出结果:
-50 -40 -20 -15 -10 -10 -5 0 0 0 0 4 5 5 10 15 15 16 20 20 25 25 30 35 50
[ -50 0 50 ]
[ -50 15 35 ]
[ -50 20 30 ]
[ -50 25 25 ]
[ -40 -10 50 ]
[ -40 5 35 ]
[ -40 10 30 ]
[ -40 15 25 ]
[ -40 20 20 ]
[ -20 -15 35 ]
[ -20 -10 30 ]
[ -20 -5 25 ]
[ -20 0 20 ]
[ -20 4 16 ]
[ -20 5 15 ]
[ -15 -10 25 ]
[ -15 -5 20 ]
[ -15 0 15 ]
[ -15 5 10 ]
[ -10 -10 20 ]
[ -10 -5 15 ]
[ -10 0 10 ]
[ -10 5 5 ]
[ -5 0 5 ]
[ 0 0 0 ]