数组中和等于K的数对

给出一个整数K和一个无序数组A,A的元素为N个互不相同的整数,找出数组A中所有和等于K的数对。例如K = 8,数组A:{-1,6,5,3,4,2,9,0,8},所有和等于8的数对包括(-1,9),(0,8),(2,6),(3,5)。

输入

第1行:用空格隔开的2个数,K N,N为A数组的长度。(2 <= N <= 50000,-10^9 <= K <= 10^9)
第2 - N + 1行:A数组的N个元素。(-10^9 <= A[i] <= 10^9) 

输出

第1 - M行:每行2个数,要求较小的数在前面,并且这M个数对按照较小的数升序排列。
如果不存在任何一组解则输出:No Solution

输入样例

8 9
-1
6
5
3
4
2
9
0
8

输出样例

-1 9
0 8
2 6
3 5
#include <cmath>
#include <vector>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;

int main() {
    int k ,n;
    cin>>k>>n;
    vector<int>f(n);
    vector<PII>res;
    for(int i=0;i<n;i++)cin>>f[i];
    unordered_map<int,int>hash;
    sort(f.begin(),f.end());
    for(int i=0;i<n;i++){
        if(hash.find(k-f[i])!=hash.end()){
            res.push_back({k-f[i],f[i]});
        }
        hash[f[i]]++;
    }
    if(!res.size())cout<<"No Solution"<<endl;
    else {
        sort(res.begin(),res.end());
        for(int i=0;i<res.size();i++){
            cout<<res[i].first<<' '<<res[i].second<<endl;
        }
    }


    return 0;
}

 

posted @ 2019-07-19 20:59  YF-1994  阅读(437)  评论(0编辑  收藏  举报