(1)和为S的两个数字
bool findNumberWithSum(int data[], int length, int sum, int &numb1, int &numb2){ // data 中的数字序列递增 if(data == NULL || length <1) return NULL ; int low = 0; int high = length - 1; while(low < high){ int tp = data[low] + data[high] ; if( tp == sum){ numb1 = data[low]; numb2 = data[high]; return true; }else if(tp < sum){ low++; }else{ high--; } } return false; }
(2)和为S的连续整数序列
和(1)一样双指针思想。不过这里双指针分别指向整数序列的开头和结尾
void print(int small, int big){ while(small <= big){ printf("%d ",small); small++; } } bool findContinue(int sum){ if(sum < 3) return; int small = 1; int big = 2; int mid = (1+sum)>>1; int curSum = 3; while(small < mid){ if(curSum == sum) print(small, big); while(curSum > sum && small < mid){ curSum -= small; small++; if(curSum == sum) print(small, big); } ++big; curSum += big; } }