来自剑指offer
#include "stdafx.h"
#include <iostream>
using namespace std;
bool FindNumbersWithSum(int* data, int length, int sum, int* num1, int* num2)
{
bool bFound = false;
if(data==NULL || length < 1)
return bFound;
int ahead = length-1;
int behind = 0;
while ( ahead > behind )
{
int curSum = data[ahead] + data[behind];
if (curSum == sum)
{
*num1 = data[behind];
*num2 = data[ahead];
bFound = true;
break;
}
else if (curSum > sum)
ahead--;
else
behind++;
}
return bFound;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[] = {1,2,4,7,11,15};
int num1, num2;
if ( FindNumbersWithSum(a,6,15,&num1,&num2) )
{
cout <<"num1 = "<<num1<<" num2 = "<<num2<<endl;
}
else
cout <<"not found!"<<endl;
return 0;
}
分析:与上述思路基本类似,把small,big分别初始化为1,2。例如,我们求和为9的全序列,那么small和big的变化如下图所示。
代码:
#include "stdafx.h"
#include <iostream>
using namespace std;
void PrintContinuousSequence(int small, int big)
{
cout <<"Continusou Sequence is: ";
for (; small <= big; small++)
cout << small <<" ";
cout << endl;
}
void FindContinuousSequence(int sum)
{
if (sum < 3)
return;
int small = 1;
int big = 2;
int middle = (1+sum)>>1;
int curSum = small + big;
while ( small < middle )
{
if ( curSum == sum )
{
PrintContinuousSequence(small,big);
big++;
curSum +=big;
}
else if ( curSum > sum )
{
curSum -= small;
small++;
}
else
{
big++;
curSum += big;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
FindContinuousSequence(15);
return 0;
}