2010-11-3017:52:25
题目:输入一个已经按升序排序过的数组和一个数字,
在数组中查找两个数,使得它们的和正好是输入的那个数字。
要求时间复杂度是O(n)。如果有多对数字的和等于输入的数字,输出任意一对即可。
例如输入数组1、2、4、7、11、15和数字15。由于4+11=15,因此输出4和11。
//输入一个已经按升序排序过的数组和一个数字
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int num[8]={1,3,4,5,6,7,8,10};
while(1)
{
int base1=0,base2=7;
int total;
cin>>total;
bool flags=false;
while(1)
{
if(base1>=base2)
break;
if(num[base1]+num[base2]==total)
{
flags=true;
break;
}
else if(num[base1]+num[base2]>total)//如果前后相加大于要求值,则必然是该值前面的
--base2;
else
++base1;
}
if(flags)
{
cout<<num[base1]<<"和"<<num[base2]<<endl;
}
else
cout<<"没有找到"<<endl;
}
return 0;
}