Quick actions

cmd+k|ctrl+k

Navigation

Languages

K Closest Number 

Snippet info

Language

Cpp

Visibility

public

Author

amangoyal1727

Created

2021-01-11T20:04:32Z

Updated

2021-01-11T20:05:48Z

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    
    int k;
    cin>>k;
    
    int x;
    cin>>x;
    
    int n;
    cin>>n;
    
    int A[n];
    for(int i=0 ; i<n; i++){
        cin>>A[i];
    }
    
    priority_queue<pair<int,int>> maxh;
    
    for(int i=0; i<n; i++){
        maxh.push( {abs(A[i]-x) , A[i]} );
        if(maxh.size()>k)
            maxh.pop();
    }
    
    while(k>0){
        cout<<maxh.top().second<<" ";
        maxh.pop();
        k--;
        
    }
    
}
INFO