-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path25. 735. Asteroid Collision
45 lines (39 loc) · 1.18 KB
/
25. 735. Asteroid Collision
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
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> st = new Stack<Integer>();
for(int asteroid:asteroids){
//right //empty
if(st.isEmpty()|| asteroid>0){
st.push(asteroid);
}else{
//right and left (collision possible)
while(!st.isEmpty() && st.peek()>0){
int right = st.peek();
//equal
if(right == -asteroid){
asteroid = 0;
st.pop();
break;
}
//less (r < l)
else if(right < -asteroid){
st.pop();
}
//r > l
else{
asteroid = 0;
break;
}
}
if(asteroid !=0){
st.push(asteroid);
}
}
}
int res[] = new int[st.size()];
for(int i=st.size()-1;i>=0;i--){
res[i] = st.pop();
}
return res;
}
}