/*
41:和为s的两个数 ; 和为s的连续正整数序列
{1,2,4,7,11,15} 求和为15的两个数(头尾指针)
*/
bool FindTwoNumOfSum(int ar[], int len, int sum, int *num1, int *num2)
{
bool flag = false;
if (ar == NULL || len <= 0 || num1 == NULL || num2 == NULL)
return flag;
int head = 0;
int tail = len - 1;
while (head < tail)
{
int curSum = ar[head] + ar[tail];
if (curSum == sum)
{
*num1 = ar[head];
*num2 = ar[tail];
flag = true;
break;
}
else if (curSum>sum)
tail--;
else
head++;
}
return flag;
}
/*
打印和为n的序列
1+2+3+4+5=4+5+6=7+8=15
打印 1~5,4~6,7~8
*/
void printSeq(int small, int big)
{
for (int i = small; i <= big; ++i)
cout << i << " ";
cout << endl;
}
void FindSeqOfSum(int sum)
{
if (sum < 3)
return;
int small = 1;
int big = 2;
int times = (sum + 1) / 2; //small big两个数 只用增加到sum的一半
int curSum = small + big;
while (small < times)
{
if (curSum == sum)
printSeq(small,big);
while (curSum > sum && small < times)
{
curSum -= small;
small++;
if (curSum == sum)
printSeq(small, big);
}
big++;
curSum += big;
}
}
//
//void test()
//{
// FindSeqOfSum(15);
//}
[剑指offer]和为s的两个数 ; 和为s的连续正整数序列
最新推荐文章于 2016-04-07 16:10:16 发布