41.和为s的两个数字VS和为s的连续正数序列


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 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;
}

时间复杂度为O(n).



void FindContinuousSequence(int sum)
{
if (sum < 3)
return;
int small = 1;
int big = 2;
int middle = (1 + sum) / 2;
int curSum = small + big;
while (sum<middle)
{
if (curSum == sum)
PrintContinuousSequence(small, big);
while (curSum > sum&&small < middle)
{
curSum -= small;
small++;
if (curSum == sum)
PrintContinuousSequence(small, big);
}
big++;
curSum += big;
}
}
void PrintContinuousSequence(int small,int big)
{
for (int i = small; i <= big; ++i)
printf("%d",i);
printf("\n");
}

阅读更多
文章标签: 数组
个人分类: 剑指offer
博主设置当前文章不允许评论。

没有更多推荐了,返回首页

不良信息举报

41.和为s的两个数字VS和为s的连续正数序列

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭