Skip to content

Commit ea91337

Browse files
committed
Runtime: 120 ms (Top 34.05%) | Memory: 44.1 MB (Top 63.23%)
1 parent b313914 commit ea91337

File tree

1 file changed

+16
-15
lines changed

1 file changed

+16
-15
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,50 @@
1+
// Runtime: 120 ms (Top 34.05%) | Memory: 44.1 MB (Top 63.23%)
12
/**
23
* @param {number[]} asteroids
34
* @return {number[]}
45
*/
56
var asteroidCollision = function(asteroids) {
6-
7+
78
const s = [];
89
for (let i = 0; i < asteroids.length; i++) {
910
const a = asteroids[i];
10-
11-
// Negative asteroids to the left of the stack can be ignored.
11+
12+
// Negative asteroids to the left of the stack can be ignored.
1213
// They'll never collide. Let's just add it to the answer stack and
1314
// move on. I consider this a special case.
1415
if ((s.length === 0 || s[s.length -1] < 0) && a < 0 ) {
1516
s.push(a);
16-
17+
1718
// If an asteroid a is positive (l to r), it may still collide with an
1819
// a negative asteroid further on in the asteroids array
1920
} else if (a > 0) {
2021
s.push(a);
21-
22-
// a is negative. It can only collide with positive ones in
23-
// the stack. The following will keep on iterating
22+
23+
// a is negative. It can only collide with positive ones in
24+
// the stack. The following will keep on iterating
2425
// until it is dealt with.
2526
} else {
2627
const pop = s.pop();
27-
28+
2829
// positive pop beats negative a, so pick up pop
2930
// and re-add it to the stack.
3031
if (Math.abs(pop) > Math.abs(a)) {
3132
s.push(pop);
32-
33+
3334
// a has larger size than pop, so pop will get dropped
34-
// and we'll retry another iteration with the same
35+
// and we'll retry another iteration with the same
3536
// negative a asteroid and whatever the stack's state is.
3637
} else if (Math.abs(pop) < Math.abs(a)) {
3738
i--;
3839
// magnitude of positive pop and negative a are the same
3940
// so we can drop both of them.
40-
} else {
41+
} else {
4142
continue;
4243
}
4344
}
4445
}
45-
46-
// The stack should be the answer
46+
47+
// The stack should be the answer
4748
return s;
48-
49-
};
49+
50+
};

0 commit comments

Comments
 (0)