2023-08-08
프로그래머스 1단계 달리기 경주
프로그래머스JavaScript1단계코딩테스트
달리기 경주
풀이
이중 for문을 사용하면 시간복잡도는 O(N^2)이 되어 9~13번 테스트에서 시간초과가 발생합니다.
객체를 활용하여 최적화:
- 호출된 선수의 등수 감소
- 이전 순위를 찾아서 갱신
- 순위 정보 갱신 후 배열로 반환
function solution(players, callings) {
let currentPlayers = {}
let rank = {}
for(let i in players){
// 등수
currentPlayers[players[i]] = Number(i) + 1
// 사람
rank[Number(i) + 1] = players[i]
}
for(let call of callings){
// 호출된 선수의 등수 감소
currentPlayers[call]--
// 호출된 선수의 이전 순위를 찾아서 갱신
currentPlayers[rank[currentPlayers[call]]] = Number(currentPlayers[call]) + 1
// 순위 정보 갱신
rank[Number(currentPlayers[call]) + 1] = rank[currentPlayers[call]]
rank[currentPlayers[call]] = call
}
return Object.values(rank);
}