알고리즘

[프로그래머스] 달리기 경주

HHB 2024. 4. 29. 20:50

[시간 초과]

def swap(array, preIdx, postIdx):
    temp = array[preIdx]
    array[preIdx] = array[postIdx]
    array[postIdx] = temp

    return array

def solution(players, callings):
    answer = []
    
    for call in callings:
        postIdx = players.index(call)
        answer = swap(players, postIdx-1, postIdx)
        
    return answer

 

검색해보니 딕셔너리로 만들면 시간 복잡도가 줄어든다고 해서 시도.

 

[정답]

def solution(players, callings):
    dicPlayers = {player: i for i, player in enumerate(players)} 
    
    for call in callings:
        postIdx = dicPlayers[call] 
        
        dicPlayers[call] -= 1 #호명된 선수 등수 앞으로 
        dicPlayers[players[postIdx-1]] += 1 #호명된 선수의 앞 선수 뒤로
        
        players[postIdx-1], players[postIdx] = players[postIdx], players[postIdx-1] #결과값 바꿔주기
    return players

 

728x90
반응형
LIST