Skip to content

Commit 9804c29

Browse files
committed
Runtime: 50 ms (Top 58.02%) | Memory: 63.90 MB (Top 17.28%)
1 parent cca3831 commit 9804c29

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// Runtime: 50 ms (Top 58.02%) | Memory: 63.90 MB (Top 17.28%)
2+
3+
class Solution {
4+
public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {
5+
List<Robot> robots = new ArrayList();
6+
for(int i=0;i<positions.length;i++) {
7+
robots.add(new Robot(i, positions[i], healths[i], directions.charAt(i)));
8+
}
9+
Collections.sort(robots);
10+
List<Robot> survived = new ArrayList<>();
11+
Stack<Robot> stack = new Stack<>();
12+
for(Robot robot: robots) {
13+
if(robot.dir == 'R') {
14+
stack.push(robot);
15+
continue;
16+
}
17+
while(!stack.isEmpty() && robot.hlt > 0) {
18+
Robot peek = stack.peek();
19+
if(peek.hlt == robot.hlt) {
20+
stack.pop();
21+
robot.hlt = 0;
22+
} else if(peek.hlt > robot.hlt) {
23+
robot.hlt = 0;
24+
peek.hlt -= 1;
25+
} else {
26+
stack.pop();
27+
robot.hlt -= 1;
28+
}
29+
}
30+
if(robot.hlt > 0) survived.add(robot);
31+
}
32+
while(!stack.isEmpty()) {
33+
survived.add(stack.pop());
34+
}
35+
Collections.sort(survived, (o1, o2) -> o1.idx - o2.idx);
36+
return survived.stream().map(robot -> robot.hlt).collect(Collectors.toList());
37+
}
38+
}
39+
40+
class Robot implements Comparable<Robot> {
41+
public int idx;
42+
public int pos;
43+
public int hlt;
44+
public char dir;
45+
46+
public Robot(int i, int p, int h, char d) {
47+
idx = i;
48+
pos = p;
49+
hlt = h;
50+
dir = d;
51+
}
52+
53+
@Override
54+
public int compareTo(Robot robot) {
55+
return this.pos - robot.pos;
56+
}
57+
}

0 commit comments

Comments
 (0)