-
Notifications
You must be signed in to change notification settings - Fork 1
/
AsteroidCollision.java
39 lines (33 loc) · 1.02 KB
/
AsteroidCollision.java
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
32
33
34
35
36
37
38
39
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.Stack;
// https://leetcode.com/problems/asteroid-collision/
public class AsteroidCollision {
private final int[] input;
public AsteroidCollision(int[] input) {
this.input = input;
}
public int[] solution() {
Stack<Integer> stack = new Stack<>();
for (int ast : input) {
collision:
{
while (!stack.isEmpty() && ast < 0 && 0 < stack.peek()) {
int peek = stack.peek();
if (peek < -ast) {
stack.pop();
continue;
} else if (peek == -ast) {
stack.pop();
}
break collision;
}
stack.push(ast);
}
}
int[] result = new int[stack.size()];
for (int i = result.length - 1; i >= 0; i--) {
result[i] = stack.pop();
}
return result;
}
}