[파이썬 코딩테스트] 1.달리기 경주 - 프로그래머스

링크

내 풀이(X)

  • 동작은 정상적으로 하는데 실행시간이 길다고 실패함
  • 데이터가 많아지면 배열에서 인덱스를 찾는데 오래 걸리나?
def solution(players, callings):
    answer = []

    for called in callings:
        idx = players.index(called)
        players[idx-1], players[idx] = players[idx], players[idx-1]

    answer = players
    return answer

정답

def solution(players, callings):
    player_dic = {name: idx for idx, name in enumerate(players)}

    for called in callings:
        print(player_dic)
        # -> {'mumu': 0, 'soe': 1, 'poe': 2, 'kai': 3, 'mine': 4}

        i = player_dic[called]
        player_dic[called] -= 1
        print(player_dic)
        # -> {'mumu': 0, 'soe': 1, 'poe': 2, 'kai': 2, 'mine': 4}

        player_dic[players[i-1]] += 1
        print(player_dic)
        # -> {'mumu': 0, 'soe': 1, 'poe': 3, 'kai': 2, 'mine': 4}

        players[i-1], players[i] = players[i], players[i-1]

    return players


# 출력용
solution(["mumu", "soe", "poe", "kai", "mine"], ["kai", "kai", "mine", "mine"])

links

social