Leet Code Daily 2024-07-13 - Robot Collisions
Solution
Sort & Stack.
Code
struct robot {
int position;
int health;
char direction;
};
class Solution {
public:
vector<int> survivedRobotsHealths(vector<int>& positions,
vector<int>& healths, string directions) {
const int n = positions.size();
vector<robot> robots;
for (int i = 0; i < n; i++) {
robots.push_back(robot{
.position = positions[i],
.health = healths[i],
.direction = directions[i],
});
}
sort(robots.begin(), robots.end(),
[](auto& x, auto& y) { return x.position < y.position; });
stack<robot> stack;
for (auto& robot : robots) {
if (robot.direction == 'R') {
stack.push(robot);
continue;
}
while (!stack.empty() && stack.top().direction == 'R' &&
stack.top().health < robot.health) {
robot.health--;
stack.pop();
}
if (!stack.empty() && stack.top().direction == 'R') {
if (stack.top().health == robot.health) {
stack.pop();
} else {
stack.top().health--;
}
} else {
stack.push(robot);
}
}
unordered_map<int, int> health_map;
for (; !stack.empty(); stack.pop()) {
health_map[stack.top().position] = stack.top().health;
}
vector<int> ret;
for (int i = 0; i < n; i++) {
auto ptr = health_map.find(positions[i]);
if (ptr != health_map.end()) {
ret.push_back(ptr->second);
}
}
return ret;
}
};