-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
47 lines (45 loc) · 1.27 KB
/
Copy pathsolution.java
File metadata and controls
47 lines (45 loc) · 1.27 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
47
// 735. Asteroid Collision
// https://leetcode.com/problems/asteroid-collision/
// Medium | Java | Accepted 2026-02-14
// Runtime 5 ms | Memory 47.1 MB
class Solution {
//[-4, 3, -6, 2,-1,4]
//-4 -6 2
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack<>();
for(int i = 0; i<asteroids.length; i++)
{
if(asteroids[i]<0 && !stack.isEmpty())
{
while(!stack.isEmpty() && Math.abs(asteroids[i])>stack.peek() && stack.peek()>0)
{
stack.pop();
}
if(stack.isEmpty())
{
stack.add(asteroids[i]);
}
else if(stack.peek()<0)
{
stack.add(asteroids[i]);
}
else if(Math.abs(asteroids[i])==stack.peek())
{
stack.pop();
}
}
else
{
stack.add(asteroids[i]);
}
}
int[] arr = new int[stack.size()];
int i = arr.length-1;
while(!stack.isEmpty())
{
arr[i] = stack.pop();
i--;
}
return arr;
}
}