
def solution(players, callings):
for person in (callings):
index = players.index(person)
temp = players[index-1]
players[index-1] = players[index]
players[index] = temp
answer = players
return answer
시간 초과
원인
index 시간 복잡도:O(n)
찾아보니 index를 사용하면 시간초과가 나오도록 유도한 문제였다. dictionary를 사용해야한다.
def solution(players, callings):
result = {}
i=0
for player in players:
result[player] = i
i+=1
for calling in callings:
rank = result[calling]
result[calling]-=1
result[players[rank-1]]+=1
players[rank-1], players[rank] = players[rank], players[rank-1]
return players
dictionary
enumerate
result = {player: i for i, player in enumerate(players)} # 선수: 등수
쓰면 더 좋을 것 같다.
swap
python에서는 temp 안쓰고 아래와 같이 쓰면 swap된다.
a,b = b,a