[LeetCode] 735. Asteroid Collision(Kotlin)

0

LeetCode

목록 보기
32/58
post-thumbnail

[LeetCode] 735. Asteroid Collision(Kotlin)

풀이

  • asteroid를 나타내는 정수의 부호가 다르다고 충돌이 발생하는 것은 아니다!
    두 asteroid가 이동하는 방향 생각하기
    • <- ->: 충돌 발생 X
    • -> <-: 충돌 발생 O
import java.util.Deque
import kotlin.math.*

class Solution {
    fun asteroidCollision(asteroids: IntArray): IntArray {
        val st = ArrayDeque<Int>()
        asteroids.forEach{ cur ->
            while(true){
                if(st.isEmpty()){
                    st.addLast(cur)
                    break
                }

                var top = st.last()
                st.removeLast()

                // no collision
                if(!(top.isRight() && cur.isLeft())){
                    st.addLast(top)
                    st.addLast(cur)
                    break
                }
                // collision (-> <-)
                if(abs(top) > abs(cur)){
                    st.addLast(top)
                    break
                }
                else if(abs(top) == abs(cur)){
                    break
                }
                else{
                    continue
                }
            }
        }
        return st.toIntArray()
    }

    private fun Int.isLeft(): Boolean = (this < 0)
    private fun Int.isRight(): Boolean = (this > 0)
}
profile
Be able to be vulnerable, in search of truth

0개의 댓글