forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
closest-room.cpp
83 lines (79 loc) · 2.69 KB
/
closest-room.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Time: O(nlogn + klogk + klogn)
// Space: O(n + k)
class Solution {
public:
vector<int> closestRoom(vector<vector<int>>& rooms, vector<vector<int>>& queries) {
static const auto& by_size_desc = [](const auto& a, const auto& b) { return a[1] > b[1]; };
sort(begin(rooms), end(rooms), by_size_desc);
for (int i = 0; i < size(queries); ++i) {
queries[i].emplace_back(i);
}
sort(begin(queries), end(queries), by_size_desc);
set<int> ids;
vector<int> result(size(queries), -1);
int i = 0;
for (const auto& q : queries) {
int r = q[0], s = q[1], idx = q[2];
for (; i < size(rooms) && rooms[i][1] >= s; ++i) {
ids.emplace(rooms[i][0]);
}
result[idx] = find_closest(ids, r);
}
return result;
}
private:
int find_closest(const set<int>& ids, int r) {
int result = -1, min_diff = numeric_limits<int>::max();
auto it = ids.upper_bound(r);
if (it != begin(ids) && abs(*prev(it) - r) < min_diff) {
min_diff = abs(*prev(it) - r);
result = *prev(it);
}
if (it != end(ids) && abs(*it - r) < min_diff) {
min_diff = abs(*it - r);
result = *it;
}
return result;
}
};
// Time: O(nlogn + klogk + klogn)
// Space: O(n + k)
class Solution2 {
public:
vector<int> closestRoom(vector<vector<int>>& rooms, vector<vector<int>>& queries) {
static const auto& by_size_asc = [](const auto& a, const auto& b) { return a[1] < b[1]; };
sort(begin(rooms), end(rooms), by_size_asc);
for (int i = 0; i < size(queries); ++i) {
queries[i].emplace_back(i);
}
sort(begin(queries), end(queries), by_size_asc);
set<int> ids;
for (const auto& room : rooms) {
ids.emplace(room[0]);
}
vector<int> result(size(queries), -1);
int i = 0;
for (const auto& q : queries) {
int r = q[0], s = q[1], idx = q[2];
for (; i < size(rooms) && rooms[i][1] < s; ++i) {
ids.erase(rooms[i][0]);
}
result[idx] = find_closest(ids, r);
}
return result;
}
private:
int find_closest(const set<int>& ids, int r) {
int result = -1, min_diff = numeric_limits<int>::max();
auto it = ids.upper_bound(r);
if (it != begin(ids) && abs(*prev(it) - r) < min_diff) {
min_diff = abs(*prev(it) - r);
result = *prev(it);
}
if (it != end(ids) && abs(*it - r) < min_diff) {
min_diff = abs(*it - r);
result = *it;
}
return result;
}
};