DevLog:-)

[프로그래머스][파이썬] 달리기 경주 본문

알고리즘/프로그래머스

[프로그래머스][파이썬] 달리기 경주

hyeon200 2023. 6. 14. 02:27
반응형

 

 

문제

 

코드

def solution(players, callings):
    idx = {i: player for i ,player in enumerate(players)}
    p = {player:i for i, player in enumerate(players)}
    
    for call in callings:
        loc = p[call] #호명한 선수의 등수
        loc2 = loc-1 #앞 선수 등수
        
        idx[loc] = idx[loc2]  #선수:앞 선수 뒤로 보내기
        idx[loc2] = call      #선수:호명된 선수 앞으로 보내기
        p[idx[loc]] = loc     #등수:앞 선수 등수 낮추기
        p[call] = loc2        #등수:호명된 선수 등수 올리기
        
        
    return list(idx.values())

리스트에서 호명된 선수의 위치와 앞 선수의 위치를 바꿔야하는 문제이다. 

(등수와 선수이름) 이 두 데이터에 쉽고 빠르게 접근할 수 있도록 두 개의 딕셔너리를 이용하여 풀었다!

딕셔너리 -> {index:player} , {player:index}

 

 

#추가코드

#1번
def solution(players, callings):
    pla_dic = {key: i for i, key in enumerate(players)}

    for p in callings:
        c = pla_dic[p]
        pla_dic[p] -= 1
        pla_dic[players[c-1]] += 1
        players[c-1], players[c] = players[c], players[c-1]

    return players

 

1번 코드와 같이 딕셔너리 하나만으로도 풀이가 가능하다.

 

#2번
def solution(players, callings):
    for call in callings:
        if call in players:
            x = players.index(call)-1
            y = players.index(call)
            players[x], players[y] = players[y], players[x]
            
    return players

for문을 이용한 코드로도 정답을 도출할 수 있지만 시간초과가 발생한다!

반응형