-
Notifications
You must be signed in to change notification settings - Fork 0
/
658.hpp
54 lines (49 loc) · 1.18 KB
/
658.hpp
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
49
50
51
52
53
54
#ifndef LEETCODE_658_HPP
#define LEETCODE_658_HPP
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <numeric>
#include <stack>
#include <string>
using namespace std;
class Solution {
public:
vector<int> findClosestElements(vector<int> &arr, int k, int x) {
auto ite = lower_bound(arr.begin(), arr.end(), x);
auto lite = ite, rite = ite + 1;
k--;
if (*ite != x) {
if (ite != arr.begin() && *ite - x >= x - *(ite - 1)) {
lite--;
rite--;
}
}
while (k > 0) {
if (lite == arr.begin() || rite == arr.end())
break;
if (x - *(lite - 1) <= *rite - x) {
lite--;
} else {
rite++;
}
k--;
}
if (lite == arr.begin()) {
while (k-- > 0) {
rite++;
}
}
if (rite == arr.end()) {
while (k-- > 0) {
lite--;
}
}
return vector<int>(lite, rite);
}
};
#endif //LEETCODE_658_HPP