sohyeon kim

[Python] 프로그래머스 : 달리기 경주 178871, dic, enumerate, 시간복잡도 본문

Coding Test

[Python] 프로그래머스 : 달리기 경주 178871, dic, enumerate, 시간복잡도

aotoyae 2024. 9. 13. 16:22
728x90

 

 

📝 문제

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

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

 

🫠 나의 풀이 (시간 초과)

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

    return players

 

🧞‍♂️ 다른 사람의 풀이

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

    for name in callings:
        idx = player_dic[name] # index 대신 dic 을 활용
        players[idx], players[idx - 1]  = players[idx - 1], name

        player_dic[players[idx]] = idx
        player_dic[players[idx - 1]] = idx - 1

    return players

 

 

 

🔗 https://sohyeonnn.tistory.com/48

 

[프로그래머스] 달리기 경주 Python 풀이(시간초과 해결, dictionary 사용)

문제링크: https://school.programmers.co.kr/learn/courses/30/lessons/178871 프로그래머스 코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁

sohyeonnn.tistory.com

🔗 https://school.programmers.co.kr/learn/courses/30/lessons/178871

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

728x90
반응형