forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_735.java
50 lines (47 loc) · 1.72 KB
/
_735.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
40
41
42
43
44
45
46
47
48
49
50
package com.fishercoder.solutions;
import java.util.Stack;
public class _735 {
public static class Solution1 {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack();
for (int i = 0; i < asteroids.length; i++) {
if (!stack.isEmpty() && stack.peek() > 0 && asteroids[i] < 0) {
if (Math.abs(stack.peek()) < Math.abs(asteroids[i])) {
stack.pop();
stack.push(asteroids[i]);
collide(stack);
} else if (Math.abs(stack.peek()) == Math.abs(asteroids[i])) {
stack.pop();
}
} else {
stack.push(asteroids[i]);
}
}
int[] result = new int[stack.size()];
int i = stack.size();
while (!stack.isEmpty()) {
result[--i] = stack.pop();
}
return result;
}
private void collide(Stack<Integer> stack) {
do {
Integer top = stack.pop();
if (!stack.isEmpty() && stack.peek() * top < 0) {
if (stack.peek() < Math.abs(top)) {
stack.pop();
stack.push(top);
} else if (stack.peek() == Math.abs(top)) {
stack.pop();
break;
} else {
break;
}
} else if (stack.isEmpty() || stack.peek() * top > 0) {
stack.push(top);
break;
}
} while (!stack.isEmpty());
}
}
}