[DS] map 자료구조 사용하기

SINGING BIRD·2023년 4월 16일

Array.indexOf 메소드를 사용하다가 시간이 오래 걸려 최적화를 하였다.

최적화 내용은 단순하다.

  • array.indexOf 를 사용하는 대신, map 데이터 구조의 playerIndices 객체를 만들어 사용하였다.
// playerIndices 구조
// { mumu: 0, soe: 1, poe: 2, kai: 3, mine: 4 }
  • indexOf 를 한번 사용시 players.length 만큼 실행해야 하므로, callings.map 반복문 안에서 indexOf 를 사용하면
    map 반복회수 * players.length 만큼 검색을 해야한다.

  • map 데이터 구조를 사용하면, 선언할 때 한번만 players.length 만큼 실행하고, callings.map 반복문 안에서는 바로 꺼내 쓸 수 있어서 map 반복회수 만큼만 검색을 하면 된다.


기존 코드

function solution(players, callings) {
  
    let answer = players;
    
    callings.map(item => {
        const callingIndex = players.indexOf(item)
        
        const tempPlayer = answer[callingIndex - 1];
        answer[callingIndex] = tempPlayer;
        answer[callingIndex - 1] = item;
    })
    
    return answer;
}

기존 코드 실행 결과


최적화 후 코드

function solution(players, callings) {
    
    const playerIndices = {};
    for (let i = 0; i < players.length; i++) {
        playerIndices[players[i]] = i;
    }
    
    let answer = players;
    
    callings.map(item => {
        // 인덱스 get
        const callingIndex = playerIndices[item];        
        
        // 값 바꾸기
        const tempPlayer = answer[callingIndex - 1];
        answer[callingIndex] = tempPlayer;
        answer[callingIndex - 1] = item;
        
        // 인덱스 바꾸기
        playerIndices[tempPlayer]  = playerIndices[tempPlayer] + 1
        playerIndices[item]  = playerIndices[item] - 1
    })
    
    return answer;
}

최적화 후 실행 결과

profile
good things take time

0개의 댓글