forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsteroid Collision.java
More file actions
46 lines (41 loc) · 1.14 KB
/
Asteroid Collision.java
File metadata and controls
46 lines (41 loc) · 1.14 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
class Solution {
public int[] asteroidCollision(int[] asteroids) {
int[] ans;
int i = 0;
Stack<Integer> stack = new Stack<>();
while (i < asteroids.length) {
if (stack.isEmpty()) {
stack.push(asteroids[i]);
}
else if (asteroids[i] < 0) {
if (stack.peek() > 0) {
int temp = stack.pop();
if (temp > Math.abs(asteroids[i])) {
stack.push(temp);
}
else if (temp == Math.abs(asteroids[i])) {
i++;
continue;
}
else {
continue;
}
}
else {
stack.push(asteroids[i]);
}
}
else {
stack.push(asteroids[i]);
}
i++;
}
ans = new int[stack.size()];
i = stack.size()-1;
while (i >= 0) {
ans[i] = stack.pop();
i--;
}
return ans;
}
}