정수 배열 asteroids가 주어지며, 이 배열은 한 행에 있는 운석들을 나타냅니다.
각 운석은 크기를 절댓값으로, 방향을 부호로 나타냅니다 (양수는 오른쪽으로, 음수는 왼쪽으로). 각 운석은 동일한 속도로 이동합니다.
충돌 후의 운석 상태를 찾습니다. 두 운석이 충돌하면 더 작은 운석이 폭발합니다. 크기가 같으면 둘 다 폭발합니다. 같은 방향으로 이동하는 두 운석은 충돌하지 않습니다.
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.
Example 1:
Input: asteroids = [5,10,-5]
Output: [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
Input: asteroids = [8,-8]
Output: []
Explanation: The 8 and -8 collide exploding each other.
Example 3:
Input: asteroids = [10,2,-5]
Output: [10]
Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
풀이과정 설명:
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stk = new Stack<>();
for(int asteroid : asteroids){
if(stk.isEmpty() || asteroid > 0){
stk.push(asteroid);
}else{
boolean isBreak = false;
while (!stk.isEmpty() && stk.peek() > 0) {
int topS = stk.pop();
if(topS == -asteroid) {
isBreak = true;
break;
}else if(topS > -asteroid){
stk.push(topS);
isBreak = true;
break;
}
}
if (!isBreak&& (stk.isEmpty() || stk.peek() < 0)) {
stk.push(asteroid);
}
}
}
int[] retVal = new int[stk.size()];
for(int i = stk.size() -1 ; i >= 0; i--){
retVal[i] = stk.pop();
}
return retVal;
}
}
649. Dota2 Senate (0) | 2023.11.18 |
---|---|
933. Number of Recent Calls (0) | 2023.11.17 |
2390. Removing Stars From a String (0) | 2023.11.16 |
1657. Determine if Two Strings Are Close (0) | 2023.11.13 |
724. Find Pivot Index (0) | 2023.11.11 |