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

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

 

프로그래머스

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

programmers.co.kr

현재 선수들의 순위대로 이름이 들어있는 players리스트가 있고 앞선수를 앞지르는 선수들을 부르는 callings list가 있다.

결과 순위를 answer에 돌려보내면 된다.

list로 풀었는데 시간오버

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

dictionary로 만들어서 통과

def solution(players, callings):
    answer = []
    pindex =  [i for i in range(0,len(players))] 
    playerdic = { name:i for i,name in enumerate(players)}
    indexdic = { i:name for i,name in enumerate(players)}
    cindex = [ playerdic[i] for i in callings]
    for name in callings:
        val = playerdic[name]      
        playerdic[name] = val-1
        playerdic[indexdic[val-1]] = val
        indexdic[val], indexdic[val-1] =  indexdic[val-1],indexdic[val]
    num = len(players)
    for i in range(0,num):
        answer.append(indexdic[i])
    return answer

players리스트 순위를 직접 조작해 순위 dictionay를 생략

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

 

+ Recent posts