알고리즘💻/기타

프로그래머스 Lv.1 - 달리기 경주

호프 2023. 9. 27. 20:34

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

 

프로그래머스

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

programmers.co.kr

단순하게 players 배열을 순회하는 방식으로 구현을 한다면, 당연하게 시간초과가 나는 문제였다.

파이썬의 dictionary 자료구조를 이용해서 인덱스를 value로, 이름을 key로 갖는 dict로 바꿔서 인덱스를 더 빠르게 알아낼 수 있도록 구현해야 한다.

 

enumerate 메소드를 사용해서 리스트를 dictionary로 변환하는 문법에 익숙하지 않아 구글링을 했는데, 앞으로 많이 쓰일 것 같으니 외워두는 게 좋을 것 같다.

 

def solution(players, callings):
    index = {value: index for index, value in enumerate(players)}
    for i in range(len(callings)):
        idx = index[callings[i]]
        players[idx], players[idx - 1] = players[idx - 1], players[idx]
        index[callings[i]] -= 1
        index[players[idx]] += 1
    return players