상세 컨텐츠

본문 제목

735. Asteroid Collision

LeetCode

by 10002s 2023. 11. 16. 00:13

본문

Asteroid Collision - LeetCode

 

정수 배열 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.

 

풀이과정 설명:
  1. 스택을 사용하여 충돌을 시뮬레이션합니다.
  2. 스택에는 충돌을 피한 운석만 포함합니다.
  3. 새로운 운석이 들어올 때마다 스택의 맨 위 운석과 충돌 여부를 확인합니다.
  4. 충돌이 발생하면 작은 크기의 운석이 폭발합니다.
  5. 모든 운석에 대한 충돌 시뮬레이션 후, 스택에 남아 있는 운석들을 결과로 반환합니다.
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;
    }
}

 

 

반응형

'LeetCode' 카테고리의 다른 글

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

관련글 더보기