• 문제

얀에서는 매년 달리기 경주가 열립니다. 해설진들은 선수들이 자기 바로 앞의 선수를 추월할 때 추월한 선수의 이름을 부릅니다. 예를 들어 1등부터 3등까지 "mumu", "soe", "poe" 선수들이 순서대로 달리고 있을 때, 해설진이 "soe"선수를 불렀다면 2등인 "soe" 선수가 1등인 "mumu" 선수를 추월했다는 것입니다. 즉 "soe" 선수가 1등, "mumu" 선수가 2등으로 바뀝니다.

선수들의 이름이 1등부터 현재 등수 순서대로 담긴 문자열 배열 players와 해설진이 부른 이름을 담은 문자열 배열 callings가 매개변수로 주어질 때, 경주가 끝났을 때 선수들의 이름을 1등부터 등수 순서대로 배열에 담아 return 하는 solution 함수를 완성해주세요.

 

입출력 예
players callings result
["mumu", "soe", "poe", "kai", "mine"] ["kai", "kai", "mine", "mine"] ["mumu", "kai", "mine", "soe", "poe"]

 

  • 답안
def solution(players, callings):
    answer = []
    pl_dict = {value: idx for idx, value in enumerate(players)}
    
    for call in callings:
        ord_now = pl_dict[call]
        ord_fast = ord_now - 1 
        
        players[ord_now] = players[ord_fast] 
        players[ord_fast] = call
        
        pl_dict[call] -= 1
        pl_dict[players[ord_now]] += 1
        
    answer = players
    
    return answer

 

  • 이 문제 키워드
    • 해시로 해결하는 문제였음. 그러나, dict 는 key -> value 기능이 있지만 value -> key 조회 기능은 따로없음
    • key -> value 조회를 위해 dict를 설정하고, value -> key로 값 조회, 수정 할 때는 list에 작업
    • dict 에서 순위(value) 값에 변화를 주고, list에서 이 순위(index)를 조회해 변화를 주는 방향을 활용하자

+ Recent posts