-
Notifications
You must be signed in to change notification settings - Fork 7
/
k-closestElements.cpp
48 lines (42 loc) · 965 Bytes
/
k-closestElements.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <queue>
#include <vector>
#include <set>
#include <map>
using namespace std;
typedef long long int lint;
vector<int> getClosestElements(vector<int>& A, int k, int x) {
int index = lower_bound(A.begin(), A.end(), x) - A.begin();
int i = index - 1, j = index;
while (k--) {
if (i < 0 || (j < A.size() && abs(A[i] - x) > abs(A[j] - x))) {
j++;
} else {
i--;
}
}
return vector<int>(A.begin() + i + 1, A.begin() + j);
}
int main() {
int N;
cin >> N;
vector <int> A;
int x;
for (int i = 0; i < N; ++i) {
cin >> x;
A.push_back(x);
}
sort(A.begin(), A.end());
int K, X;
cin >> K >> X;
vector <int> ans = getClosestElements(A, K, X);
for (int i = 0; i < K; ++i) {
cout << ans[i] << " ";
}
cout << endl;
return 0;
}