-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAstroidCollision.java
More file actions
58 lines (49 loc) · 1.06 KB
/
AstroidCollision.java
File metadata and controls
58 lines (49 loc) · 1.06 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.Arrays;
/*
* https://leetcode.com/problems/asteroid-collision/
*/
import java.util.Stack;
public class AstroidCollision {
public static void main(String[] args) {
int[] asteroids = { 10, 2, -5 };
int[] asteroidCollision = new AstroidCollision().asteroidCollision(asteroids);
for (int i : asteroidCollision) {
System.out.print(i + ", ");
}
}
class Node {
int data;
Boolean right = null;
}
public int[] asteroidCollision(int[] asteroids) {
if (asteroids == null || asteroids.length <= 1) {
return asteroids;
}
Stack<Integer> st = new Stack<>();
int i = 0;
while (i < asteroids.length) {
int num = asteroids[i];
while (!st.isEmpty()) {
if (num < 0 && st.peek() > 0) {
int top = st.pop();
if (Math.abs(num) < top) {
num = top;
} else if (Math.abs(num) == top) {
num = 0;
}
} else {
break;
}
}
i++;
if (num != 0) {
st.push(num);
}
}
int[] res = new int[st.size()];
for (int j = res.length - 1; j >= 0; j--) {
res[j] = st.pop();
}
return res;
}
}