STL应用

/***
 给一个有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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值