关闭

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

标签: 数组
433人阅读 评论(0) 收藏 举报
分类:


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

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:155965次
    • 积分:6148
    • 等级:
    • 排名:第4027名
    • 原创:479篇
    • 转载:2篇
    • 译文:1篇
    • 评论:3条
    最新评论