-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsteroid Collision.java
More file actions
37 lines (36 loc) · 1.11 KB
/
Asteroid Collision.java
File metadata and controls
37 lines (36 loc) · 1.11 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
class Solution
{
public int[] asteroidCollision(int[] asteroids)
{
int i;
Stack<Integer> stack=new Stack<>();
for(i=0;i<=asteroids.length-1;i++)
{
if(stack.empty())
stack.push(asteroids[i]);
else if(asteroids[i]>0)
stack.push(asteroids[i]);
else if(asteroids[i]<0 && stack.peek()<0)
stack.push(asteroids[i]);
else if(asteroids[i]<0)
{
while(!stack.empty() && stack.peek()>0 && Math.abs(asteroids[i])>stack.peek())
stack.pop();
if(!stack.empty() && stack.peek()>0 && Math.abs(asteroids[i])==stack.peek())
stack.pop();
else if(!stack.empty() && Math.abs(asteroids[i])<stack.peek())
continue;
else
stack.push(asteroids[i]);
}
}
int[] res=new int[stack.size()];
i=res.length-1;
while(!stack.empty())
{
res[i]=stack.pop();
i-=1;
}
return res;
}
}