-
Notifications
You must be signed in to change notification settings - Fork 0
/
offer_57
64 lines (53 loc) · 1.12 KB
/
offer_57
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//面试题57:和为s的数字
//题目1:和为s的两个数字
bool FindNumbersWithSum(int data[],int length,int sum,int* num1,int* num2)
{
bool found=false;
if(length<1 || num1==nullptr || num2==nullptr)
return found;
int ahead=length-1;
int behind=0;
while(ahead<=behind){
long long curSum=data[ahead]+data[behind];
if(curSum==sum){
*number1=data[ahead];
*number2=data[behind];
found=true;
break;
}else if(curSum<sum){
behind++;
}else{
ahead--;
}
}
return found;
}
//题目2:和为s的连续正数序列
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<big){
if(curSum==sum)
PrintContinusSequence(small,big);
while(curSum>sum && small<middle){
curSum-=small;
small++;
if(curSum==sum)
PrintContinusSequence(small,big);
}
big++;
curSum+=big;
}
}
void PrintContinusSequence(int small,int big)
{
for(int i=small;i<=big;++i){
printf("%d ",i);
}
printf("\n");
}