호지

[프로그래머스] 달리기 경주 문제풀이 JS 본문

알고리즘/프로그래머스

[프로그래머스] 달리기 경주 문제풀이 JS

_hoji

callings 전체를 탐색해서 순서를 바꿔주면 되는 문제이다.

indexOf로 해당 player의 위치를 찾으면 시간초과이므로,

처음 players의 위치를 position 객체에 저장해두면 시간초과가 나지 않는다.

function solution(players, callings) {
  let position = {};
  players.forEach((player, i) => {
    position[player] = i;
  });
  callings.forEach((calling) => {
    const index = position[calling]--;
    const tempValue = players[index - 1];
    players[index - 1] = players[index];
    players[index] = tempValue;
    position[tempValue] = index;
  });
  return players;
}

https://school.programmers.co.kr/learn/courses/30/lessons/178871?language=javascript

Comments