## 面试题 41，和为s的两个数字，引申：和为s的连续正数序列，窗口思想(其实就是是双指针贪心)和中位数法 [LeetCode] Minimum Window Substring

O(n2)的方法自然可以解决。面试时可以先扔出来这个，然后再思考更好的解，让面试官知道你并不是不会，而是在思考更好的解。

bool FindPairForSum(int* list, int size, int s, int* index1, int* index2){
*index1 = *index2 = -1;
if(NULL == list)
return false;
int left = 0; int right = size -1;
while(left < right){
if((list[left] + list[right]) == s){
*index1 = left;
*index2 = right;
return true;
}
if(list[left] + list[right] < s){
left++;
}else{
right--;
}
}
return false;
}

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;

{
long long curSum = data[ahead] + data[behind];

if(curSum == sum)
{
*num1 = data[behind];
found = true;
break;
}
else if(curSum > sum)
else
behind ++;
}

return found;
}

4,5,6 之所以满足条件，是因为15/3 = 5，正好5可以放在中间，左右再拿一个4和6，所以满足。

#include<stdio.h>

void PrintContinuousSequence(int small, int big)
{
for(int i = small; i <= big; ++ i)
printf("%d ", i);

printf("\n");
}

void FindSeqSum(int sum){
if(sum < 3) return;
int mid = sum/2 + 1;
for(int i = 2;i <= mid;i++){
if(!(i&1)){
if((sum%i) == (i/2) && (sum/i - i/2 + 1) >= 0)
PrintContinuousSequence(sum/i - i/2 + 1, sum/i + i/2);
}else{
if(!(sum%i) && (sum/i - i/2) >= 0)
PrintContinuousSequence(sum/i - i/2, sum/i + i/2);
}
}
}

// ====================测试代码====================
void Test(char* testName, int sum)
{
if(testName != NULL)
printf("%s for %d begins: \n", testName, sum);

FindSeqSum(sum);
}

int main()
{
Test("test1", 1);
Test("test2", 3);
Test("test3", 4);
Test("test4", 9);
Test("test5", 15);
Test("test6", 100);

return 0;
}

void PrintContinuousSequence(int small, int big);

void FindContinuousSequence(int sum)
{
if(sum < 3)
return;

int small = 1;
int big = 2;
int middle = (1 + sum) / 2;
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;
}
}

void PrintContinuousSequence(int small, int big)
{
for(int i = small; i <= big; ++ i)
printf("%d ", i);

printf("\n");
}

posted on 2014-03-03 00:44  Felix Fang  阅读(1735)  评论(1编辑  收藏  举报