프로그래머스 코딩테스트 연습 - 달리기 경주 JavaScript

기존에 주어지는 배열의 순서를 바꾸어 정답을 내야하는 문제였다.

일단, 가장 간단한 방법으로 문제를 접근해보았다.

function solution(players, callings) {
    const answer = [...players];
    callings.forEach(el => {
        const idx = answer.indexOf(el);
        [answer[idx - 1], answer[idx]] = [answer[idx], answer[idx - 1]];
    })
    return answer;
}

정답은 낼 수 있었지만, 시간초과가 발생하여 다른 방법으로 문제의 해결 방법을 모색하였다.

아무래도 indexOf가 많은 비용이 발생하지 않았나 싶다.

그래서 다른 방법으로 객체를 사용하는 방법을 생각했다.

function solution(players, callings) {
    const answer = [...players];
    const map = {};
    players.forEach((el, idx) => {
        map[el] = idx;
    })
    callings.forEach(el => {
        const idx = map[el];
        map[answer[idx - 1]] = map[answer[idx - 1]] + 1; // 이전 index + 1
        map[el] = map[el] - 1; // 현재 index - 1
        [answer[idx - 1], answer[idx]] = [answer[idx], answer[idx - 1]];
    })
    return answer;
}

객체에 index를 담아서 더 빠르게 해당 값의 index를 찾아 접근할 수 있도록 하였다.

추월이 일어난 뒤에는 추월당한 key의 값을 + 1, 추월한 key의 값을 -1하여 index정보를 최신으로 관리하였다.