和为s的两个数字VS 和为S的连续正数序列
输入一个递增排序的数组和一个数字是S,在数组中查找两个数,使得它们的和正好是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 curSum = data[ahead]+data[behind]; if(curSum == sum) { *num1 = data[ahead]; *num2 = data[behind]; found =true; break; } else if (curSum > sum) ahead--; else behind++; } return found; }
主要运用前后2个指针(代码中没写成指针形式)ahead,behind减少了遍历次数,增加了效率。
输入一个正数S,打印所有和为S的连续正数序列。思路是相同的
void PrintContinuousSequence(int small,int big) { for(int i =small; i <= big; ++i) { cout<<i <<'\t'; } cout<<endl; } 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; } }