소행성 방향이 다른 경우에만 체크해주는게 좋다.
루프를 돌면서 아래 방식으로 제거할 소행성을 체크한다.
방향이 다른 동안(while),
1. 현재 소행성이 stack.peek()
보다 덩치가 큼 - 부수고(stack.pop()) 다음 타겟 진행, 부술 수 있는 소행성이 없을 때까지
2. 현재 소행성이 stack.peek()
와 덩치가 같음 - 둘 다 부수고 다음 루프 진행
3. 현재 소행성이 stack.peek()
보다 덩치가 작음 - 현재 소행성이 부숴지고 다음 루프 진행
while을 탈출했다면, 정방향이거나 스택이 비어있는 경우 --> 현재 소행성 추가 필요
다만, 위에서 2번 또는 3번 조건에 걸렸다면 현재 소행성은 부숴진 상태이므로 추가하면 안 됨.
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack<>();
for (int asteroid : asteroids) {
boolean survive = true;
while (!stack.isEmpty() && asteroid < 0 && stack.peek() > 0) {
int abs = Math.abs(asteroid);
if (stack.peek() < abs) {
stack.pop();
continue;
}
if (stack.peek() == abs) {
stack.pop();
}
survive = false;
break;
}
if (survive) {
stack.push(asteroid);
}
}
int[] answer = new int[stack.size()];
for (int i=stack.size()-1; i>=0; i--) {
answer[i] = stack.pop();
}
return answer;
}
}