본문 바로가기
LeetCode/Stack

[LeetCode][Kotlin] 735. Asteroid Collision

by jinwo_o 2024. 11. 29.

735. Asteroid Collision

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.

 

Constraints:

  • 2 <= asteroids.length <= 10^4
  • -1000 <= asteroids[i] <= 1000
  • asteroids[i] != 0

코드

class Solution {
    fun asteroidCollision(asteroids: IntArray): IntArray {
        val q = ArrayDeque<Int>()

        asteroids.forEach { num ->
            var a = num
            while (q.isNotEmpty() && a < 0 && q.last() > 0) {
                val diff = a + q.last()
                if (diff < 0) {
                    q.removeLast()
                } else if (diff > 0) {
                    a = 0
                } else {
                    a = 0
                    q.removeLast()
                }
            }

            if (a != 0) {
                q.add(a)
            }
        }

        return q.toIntArray()
    }
}

'LeetCode > Stack' 카테고리의 다른 글

[LeetCode][Kotlin] 853. Car Fleet  (0) 2024.11.29
[LeetCode][Kotlin] 22. Generate Parentheses  (0) 2024.11.28
[LeetCode][Kotlin] 1544. Make The String Great  (0) 2024.11.27