코딩 테스트/프로그래머스
[Python] 프로그래머스 lv.1 달리기 경주
위시리
2025. 3. 26. 13:26
1. 리스트 - 시간초과
→ 어떻게 접근해야 시간을 줄일 수 있을까?
2. 인덱스에 접근하는 속도를 줄이기 위해 → 딕셔러니 (해시)
중복이 허용되지 않는다 → dictionary
dic = dict(arr) 와 같이 리스트를 dictionary 로 변환 가능
해설 코드
def solution(players, callings):
answer = []
ply = {}
# 선수 이름 : 등수
for i in range(len(players)):
ply[players[i]] = i
# 추월 선수에 따른 검색
for p in callings:
idx = ply[p] # 추월한 선수 등수
front = idx-1 # 앞선수 위치
frontplayer = players[front] # 앞선수 이름
#자리 바꿈
players[front], players[idx] = players[idx], players[front]
#딕셔너리 갱신
ply[p] = front
ply[frontplayer] = idx
return players
다시 푼 코드
def solution(players, callings):
answer = []
dic = {}
for i in range(len(players)) :
dic[players[i]] = i
for c in callings :
# 1. 추월한 선수의 index 찾기 -> key의 value = idx
ply_idx = dic[c]
# 2. 추월한 선수의 위치 바꾸기 (dic)
dic[c] -= 1
# 3. 추월당한 선수의 위치 바꾸기 (dic)
players[ply_idx], players[ply_idx-1] = players[ply_idx-1], players[ply_idx]
# 4. 리스트 위치 바꾸기
dic[players[ply_idx]] += 1
return players