-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path25-731.ts
More file actions
28 lines (20 loc) · 709 Bytes
/
Copy path25-731.ts
File metadata and controls
28 lines (20 loc) · 709 Bytes
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
// https://leetcode.com/problems/asteroid-collision/?envType=study-plan-v2&envId=leetcode-75
const asteroidCollision = (asteroids: number[]): number[] => {
if (asteroids.length < 2) return asteroids;
const survivingAsteroids = [asteroids[0]];
let i = 1;
while (i < asteroids.length) {
const prev = survivingAsteroids[survivingAsteroids.length - 1];
const curr = asteroids[i];
if (prev >= 0 && curr < 0) {
const currAbsVal = Math.abs(curr);
if (prev < currAbsVal) {
survivingAsteroids.pop();
continue;
}
if (prev === currAbsVal) survivingAsteroids.pop();
} else survivingAsteroids.push(curr);
i++;
}
return survivingAsteroids;
};