-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
42 lines (37 loc) · 1.19 KB
/
Copy pathMain.java
File metadata and controls
42 lines (37 loc) · 1.19 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
// LeetCode Problem: https://leetcode.com/problems/asteroid-collision/
import java.util.Arrays;
import java.util.Stack;
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> st = new Stack<>();
for(int asteroid : asteroids){
int currAst = asteroid;
while(!st.isEmpty() && currAst < 0 && st.peek() > 0){
if(Math.abs(currAst) > st.peek()){
st.pop();
} else if (Math.abs(currAst) == st.peek()){
st.pop();
currAst = 0;
} else {
currAst = 0;
}
}
if(currAst != 0)
st.push(currAst);
}
int[] ans = new int[st.size()];
int i = st.size() - 1;
while(!st.isEmpty()){
ans[i--] = st.pop();
}
return ans;
}
}
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
int[] asteroids = {5, 10, -5};
int[] result = solution.asteroidCollision(asteroids);
System.out.println("Resulting Asteroids: " + Arrays.toString(result));
}
}