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

Seohyun·2024년 8월 23일

알고리즘

목록 보기
24/36

아래는 처음 제출한 답변이다. 리스트에서 인자로 준 값에 해당하는 원소의 인덱스를 반환하는 리스트.index(값) 함수를 사용했다. 실행했을 때 하나의 테스트케이스에서는 패스를 했지만 제출해 보니 몇 테스트케이스(9~13번)에서 시간 초과가 떴다.

def solution(players, callings):
    
    for i in range(len(callings)):
        idx = players.index(callings[i])
        tmp = players[idx]
        players[idx] = players[idx-1]
        players[idx-1] = tmp
    return players

그래서 딕셔너리를 사용해 각 player의 순위를 저장하고 players 리스트가 매 순위 변경을 반영하도록 해 봤다. 먼저 딕셔너리에 원래 순위와 player 이름을 짝지어 저장해 놓았다. called_idx와 switched_idx에 바꿔야 하는 플레이어의 원래 순위를 넣어 놓고, 순위를 저장하기 위한 players_pos 딕셔너리에 바뀐 순서를 반영한 뒤, 바뀐 순위대로 players 내 각 플레이어의 이름을 바꿔 넣었다.

def solution(players, callings):
    
    players_pos = {player:idx for idx, player in enumerate(players)}
    
    for c in callings:
        called_idx = players_pos.get(c)
        switched_idx = players_pos.get(c) - 1
        
        players_pos[c] = called_idx - 1
        players_pos[players[switched_idx]] = switched_idx + 1
        
        players[called_idx] = players[switched_idx]
        players[switched_idx] = c
        
    return players 

성공!

profile
Hail hamster

0개의 댓글