两种方法都类似于快排的变形。

#include <iostream>
#include <string>
using namespace std; bool FindNumbersWithSum(int data[],int length,int sum,int *num1,int *num2)
{
bool found=false;
if (length<||num1==NULL||num2==NULL)
{
return found;
}
int ahead=length-;
int behind=;
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<)
{
return;
}
int small=;
int big=;
int middle=(+sum)/;
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[]={,,,,,,,,,};
int m,n;
FindNumbersWithSum(str,,,&m,&n);
cout<<m<<n<<endl;
FindContinuousSequence();
return ;
}
05-15 03:49