Skip to content

Commit 12e57ec

Browse files
authored
Merge pull request neetcode-gh#1842 from gnohgnij/735-asteroid-collision
Create: 0735-asteroid-collision.java
2 parents 68d3c7b + 2cb5abd commit 12e57ec

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

java/0735-asteroid-collision.java

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public int[] asteroidCollision(int[] asteroids) {
3+
Stack<Integer> stack = new Stack<>();
4+
int index = 0;
5+
6+
while(index < asteroids.length) {
7+
int a = asteroids[index];
8+
if(stack.isEmpty()) {
9+
stack.push(a);
10+
index++;
11+
} else {
12+
if(stack.peek() > 0 && a < 0) {
13+
if(Math.abs(stack.peek()) > Math.abs(a)) {
14+
index++;
15+
} else if(Math.abs(stack.peek()) < Math.abs(a)) {
16+
stack.pop();
17+
} else {
18+
index++;
19+
stack.pop();
20+
}
21+
} else {
22+
stack.push(a);
23+
index++;
24+
}
25+
}
26+
}
27+
28+
int[] res = new int[stack.size()];
29+
for(int i=res.length-1; i>=0 ;i--) {
30+
res[i] = stack.pop();
31+
}
32+
return res;
33+
}
34+
}

0 commit comments

Comments
 (0)