We are given an array asteroids of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
publicclassSolution {
publicint[]asteroidCollision(int[] asteroids) {
Stack<Integer> stack =new Stack<>();
for (int num : asteroids) {
if (num > 0) {
stack.push(num);
} else {
while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < Math.abs(num)) {
stack.pop(); // collisions of all smaller positive asteroids going towards right }
// stack is empty or asteroid going towards leftif (stack.isEmpty() || stack.peek() < 0) {
stack.push(num);
} elseif (stack.peek() == Math.abs(num)) {
stack.pop(); // both asteroids are equal and will explode }
}
}
int[] result =newint[stack.size()];
for (int i = stack.size() - 1; i >= 0; i--) {
result[i]= stack.pop();
}
return result;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defasteroidCollision(self, asteroids: List[int]) -> List[int]:
stack: List[int] = []
for num in asteroids:
if num >0:
stack.append(num)
else:
while stack and stack[-1] >0and stack[-1] < abs(num):
stack.pop() # collisions of all smaller positive asteroids going towards right# stack is empty or asteroid going towards leftifnot stack or stack[-1] <0:
stack.append(num)
elif stack[-1] == abs(num):
stack.pop() # both asteroids are equal and will explodereturn stack