[시간 초과]
def swap(array, preIdx, postIdx):
temp = array[preIdx]
array[preIdx] = array[postIdx]
array[postIdx] = temp
return array
def solution(players, callings):
answer = []
for call in callings:
postIdx = players.index(call)
answer = swap(players, postIdx-1, postIdx)
return answer
검색해보니 딕셔너리로 만들면 시간 복잡도가 줄어든다고 해서 시도.
[정답]
def solution(players, callings):
dicPlayers = {player: i for i, player in enumerate(players)}
for call in callings:
postIdx = dicPlayers[call]
dicPlayers[call] -= 1 #호명된 선수 등수 앞으로
dicPlayers[players[postIdx-1]] += 1 #호명된 선수의 앞 선수 뒤로
players[postIdx-1], players[postIdx] = players[postIdx], players[postIdx-1] #결과값 바꿔주기
return players
728x90
'알고리즘' 카테고리의 다른 글
백준 단계 별로 풀기 시작 (0) | 2024.07.31 |
---|---|
Python으로 구현하는 큐(Queue) (0) | 2023.12.01 |
Python으로 연결리스트(LinkedList) 구현하기 (0) | 2023.11.30 |
Python으로 Stack(스택) 구현하기 (0) | 2023.11.30 |
[프로그래머스] a와 b출력하기 (1) | 2023.10.10 |