和为s的两个数字VS和为s的连续整数序列(面试题 41)

来源:互联网 发布:越南古代服饰淘宝 编辑:程序博客网 时间:2024/05/16 17:39

题目一:输入一个递增的排列和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,输出任意一对即可。

#include "iostream"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;int behind =0;while(ahead>behind){long curSum =data[ahead] +data[behind];if (curSum ==sum){*num1 =data[behind];*num2 =data[ahead];found =true;    break;}else if(curSum >sum)ahead --;elsebehind++;}return found;}void main(){int data[6] ={1,2,4,7,11,15};int num1,num2;FindNumbersWithSum(data,6,15,&num1,&num2);cout<<num1<<" "<<num2<<endl;}


0 0
原创粉丝点击