两种方法都类似于快排的变形。
#include <iostream>
#include <string>
using namespace std;
bool FindNumbersWithSum(int data[],int length,int sum,int *num1,int *num2)
{
bool found=false;
if (length<1||num1==NULL||num2==NULL)
{
return found;
}
int ahead=length-1;
int behind=0;
while(ahead>behind)
{
long curSum=data[ahead]+data[behind];
if (curSum==sum)
{
*num1=data[behind];
*num2=data[ahead];
found=true;
break;
}
else if(curSum>sum)
{
ahead--;
}
else
{
behind++;
}
}
return found;
}
void PrintContinuousSequence(int small,int big)
{
for (int i=small;i<=big;i++)
{
cout<<i<<" ";
}
cout<<endl;
}
void FindContinuousSequence(int sum)
{
if (sum<3)
{
return;
}
int small=1;
int big=2;
int middle=(1+sum)/2;
int curSum=small+big;
while(small<middle)
{
if (curSum==sum)
{
PrintContinuousSequence(small,big);
}
while(curSum>sum&&small<middle)
{
curSum-=small;
small++;
if (curSum==sum)
{
PrintContinuousSequence(small,big);
}
}
big++;
curSum+=big;
}
}
int main()
{
int str[]={1,2,3,4,5,6,7,8,9,10};
int m,n;
FindNumbersWithSum(str,10,13,&m,&n);
cout<<m<<n<<endl;
FindContinuousSequence(100);
return 0;
}