알고리즘/알고리즘 문제풀이
프로그래머스) 달리기 경주 문제풀이
sh119
2025. 2. 21. 10:52
문제)
https://school.programmers.co.kr/learn/courses/30/lessons/178871
풀이)
import java.util.*;
class Solution {
public String[] solution(String[] players, String[] callings) {
String[] answer = {};
// Map<> 으로 선수, 등수 관리
Map<String, Integer> map = new HashMap<>();
for(int i=0; i<players.length; i++){
map.put(players[i], i);
}
List<String> playerList = new ArrayList<>(Arrays.asList(players));
// 이름이 불릴때마다 Collections.swap 을 이용해 List의 선수 순서를 바꿔준다.
// ㄴ 선수, 등수 쌍 관리를 map으로 하여 List의 순서를 바꿀 인덱스 값을 관리한다
for(String name : callings){
int idx = map.get(name);
Collections.swap(playerList, idx, idx-1);
map.put(playerList.get(idx), idx);
map.put(playerList.get(idx-1), idx-1);
}
return playerList.toArray(new String[0]);
}
}