forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
robot-collisions.cpp
47 lines (44 loc) · 1.38 KB
/
robot-collisions.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
// Time: O(nlogn)
// Space: O(n)
// sort, simulation, stack
class Solution {
public:
vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) {
vector<int> idxs(size(positions));
iota(begin(idxs), end(idxs), 0);
sort(begin(idxs), end(idxs), [&](const auto& a, const auto& b) {
return positions[a] < positions[b];
});
vector<int> stk;
stk.reserve(size(idxs));
for (const auto& i : idxs) {
if (directions[i] == 'R') {
stk.emplace_back(i);
continue;
}
while (!empty(stk)) {
if (healths[stk.back()] == healths[i]) {
healths[stk.back()] = healths[i] = 0;
stk.pop_back();
break;
}
if (healths[stk.back()] > healths[i]) {
healths[i] = 0;
--healths[stk.back()];
break;
}
healths[stk.back()] = 0;
--healths[i];
stk.pop_back();
}
}
vector<int> result;
result.reserve(size(healths));
for (const auto& x : healths) {
if (x) {
result.emplace_back(x);
}
}
return result;
}
};