본문 바로가기
알고리즘/프로그래머스

[2023-06-13] [프로그래머스 lv1] 달리기 경주 (Kotlin)

by joh9911 2023. 6. 13.

 

프로그래머스 문제로 연습하는 것이 확실히 좋은 것 같아요. 

 

코테 연습도 되고, 다른 분의 풀이와 비교해보기 간편해서 너무 좋아요.

 

 


package seventieth
class Solution {
    fun solution(players: Array<String>, callings: Array<String>): Array<String> {
    	// map에 플레이어의 순위 넣기
        val map = mutableMapOf<String,Int>()

        for (index in players.indices){
            map[players[index]] = index
        }
		
        // 순위 바꿔주기
        for (index in callings.indices){
            val idx = map[callings[index]]!!
            val prevPlayer = players[idx - 1]
            
            players[idx - 1] = callings[index]
            players[idx] = prevPlayer
            
            map[callings[index]] = map.getOrDefault(callings[index], 0) - 1
            map[prevPlayer] = map.getOrDefault(prevPlayer, 0) + 1
        }
        // return할 배열에 넣어주기
        val arr = Array(players.size){""}
        map.forEach{
            arr[it.value] = it.key
        }
        return arr
    }
}

댓글