Skip to content

Commit 72e5e6c

Browse files
committed
Create: 0735-asteroid-collision.rs / .js
1 parent ee7a3bc commit 72e5e6c

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

javascript/0735-asteroid-collision.js

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @param {number[]} asteroids
3+
* @return {number[]}
4+
*/
5+
const asteroidCollision = (asteroids) => {
6+
let stack = [];
7+
8+
for (asteroid of asteroids) {
9+
while (stack.length != 0 && asteroid < 0 && stack.at(-1) > 0) {
10+
let diff = asteroid + stack.at(-1);
11+
12+
if (diff < 0) {
13+
stack.pop();
14+
} else if (diff > 0) {
15+
asteroid = 0;
16+
} else {
17+
asteroid = 0;
18+
stack.pop();
19+
}
20+
}
21+
22+
if (asteroid) {
23+
stack.push(asteroid);
24+
}
25+
}
26+
27+
return stack;
28+
};

rust/0735-asteroid-collision.rs

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
use std::cmp::Ordering;
2+
3+
impl Solution {
4+
pub fn asteroid_collision(asteroids: Vec<i32>) -> Vec<i32> {
5+
let mut stack: Vec<i32> = vec![];
6+
7+
for mut asteroid in asteroids {
8+
while !stack.is_empty() && asteroid < 0 && stack.last() > Some(&0) {
9+
let diff = asteroid + stack.last().unwrap();
10+
match diff.cmp(&0) {
11+
Ordering::Less => {
12+
stack.pop();
13+
}
14+
Ordering::Greater => asteroid = 0,
15+
Ordering::Equal => {
16+
asteroid = 0;
17+
stack.pop();
18+
}
19+
};
20+
}
21+
if asteroid != 0 {
22+
stack.push(asteroid);
23+
}
24+
}
25+
stack
26+
}
27+
}

0 commit comments

Comments
 (0)