forked from webVueBlog/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path行星碰撞.js
31 lines (31 loc) · 922 Bytes
/
行星碰撞.js
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
/**
* @param {number[]} asteroids
* @return {number[]}
735. 行星碰撞
*/
var asteroidCollision = function(asteroids) {
let stack = [];
for(let i = 0; i < asteroids.length; i++) {
let curr = asteroids[i];
if (stack.length >= 0 && stack[stack.length - 1] > 0 && curr > 0) {
stack.push(curr);
continue;
}
// 栈顶的大就不用走了 [10,2] -5 [10,5] -5 [2, 1, -5]
while(stack[stack.length - 1] > 0 && curr < 0) {
if (Math.abs(stack[stack.length - 1]) < Math.abs(curr)) {
stack.pop();
} else if (Math.abs(stack[stack.length - 1]) === Math.abs(curr)) {
stack.pop();
curr = null;
} else {
curr = null;
break;
}
}
if (curr !== null) {
stack.push(curr);
}
}
return stack;
};