/***
给一个有N个整数的数组S..和另一个整数X,判断S里有没有2个数的和为X,
请设计成O(n*log2(n))的算法。
****/
#include <iostream>
#include <algorithm>
#include <utility>
#include <map>
using namespace std;
typedef pair<int,int> Pair;
map<int,int> findSum(int *s,int n,int x)
{
sort(s,s+n); //引用了库函数
map<int ,int > m1;
int *begin=s;
int *end=s+n-1;
while(begin<end) //俩头夹逼,很经典的方法
{
if(*begin+*end>x)
{
--end;
}
else if(*begin+*end<x)
{
++begin;
}
else
{ m1.insert(map<int,int>::value_type(*begin,*end));
begin++;
// return Pair(*begin,*end);
}
}
return m1;
// return Pair(-1,-1);
}
int main()
{
int arr[100]=
{
3, -4, 7, 8, 12, -5, 0, 9
};
/***
-5 -4 0 3 7 8 9 12
***/
int n=8,x;
while(cin>>x)
{
//Pair ret=findSum(arr,n,x);
map<int,int> ret=findSum(arr,n,x);
map<int,int>::iterator it=ret.begin();
while(it!=ret.end())
{
cout<<it->first<<" "<<it->second<<endl;
it++;
}
// cout<<ret.first<<","<<ret.second<<endl;
}
return 0;
}
STL应用
最新推荐文章于 2024-09-13 16:27:15 发布