劍指Offer——面試題57:和爲 s 的數字

題目一:和爲s的兩個數字

題目:輸入一個遞增排序的數組和一個數字s,在數組中查找兩個數,使得它們的和正好是s。如果有多對數字的和等於s,輸出任意一對即可。

在這裏插入圖片描述

#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
#include<cstring>
#include<stack>
#include<cmath>
using namespace std;
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, 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;
}
int main() {
	int data[]={1, 2, 4, 7, 11, 15};
	int num1, num2;
	if(FindNumbersWithSum(data, 6, 15, &num1, &num2)) printf("%d %d", num1, num2);
	else printf("not found");
	return 0;
}

題目二:和爲 s 的連續正數序列

題目:輸入一個正數s,打印出所有和爲s的連續正數序列(至少含有兩個數)。例如輸入15,由於1+2+3+4+5=4+5+6=7+8=15,所以結果打印出3個連續序列1~5、4~6和7~8。
#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
#include<cstring>
#include<stack>
#include<cmath>
using namespace std;
void PrintContainuousSequence(int small, int big){
	for(int i=small;i<=big;i++) printf("%d ", i);
	printf("\n");
}
void FindContainuousSequence(int sum){
	if(sum<3) return ;
	
	int small=1, big=2, middle=(sum+1)/2, curSum=small+big;
	
	while(small<middle){
		if(curSum==sum) PrintContainuousSequence(small, big);
		
		while(curSum>sum && small<middle){
			curSum-=small;
			small++;
			
			if(curSum==sum) PrintContainuousSequence(small, big);
		}
		big++;
		curSum+=big;
	}
}
int main() {
	FindContainuousSequence(15);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章