Development/알고리즘

[프로그래머스 | Javascript] Lv.1 달리기 경주

레오나르도 다빈츠 2024. 12. 8. 13:20

 

 

1. indexOf로 배열자체의 위치를 바꿨다가 시간초과되고... (‼️)

2. Map으로 풀었다.

 

function solution(players, callings) {
    const playerIndexes = {};
    players.forEach((player, index) => {
        playerIndexes[player] = index;
    });

    callings.forEach(name => {
        const currentPlayerPosition = playerIndexes[name];
        const prevPlayer = players[currentPlayerPosition - 1];

        players[currentPlayerPosition] = prevPlayer;
        players[currentPlayerPosition - 1] = name;

        playerIndexes[name] = currentPlayerPosition - 1;
        playerIndexes[prevPlayer] = currentPlayerPosition;
    });

    return players;
}