Java
프로그래머스: 달리기 경주
Daeryuk Kim
2023. 11. 9. 12:33
import java.util.HashMap;
class Solution {
public String[] solution(String[] players, String[] callings) {
HashMap<String, Integer> indexMap = new HashMap<>();
for (int i=0; i<players.length; i++) {
indexMap.put(players[i], i);
}
for (String call : callings) {
int x = indexMap.get(call);
if (x > 0) {
String temp = players[x-1]; //idx:2 poe
players[x-1] = players[x]; //kai가 추월
players[x] = temp;
indexMap.put(players[x-1], x-1);
indexMap.put(players[x], x);
}
}
return players;
}
public static void main(String[] args) {
String[] players = {"mumu", "soe", "poe", "kai", "mine"};
String[] callings = {"kai", "kai", "mine", "mine"};
Solution sol = new Solution();
String[] result = sol.solution(players, callings);
for (String r : result) {
System.out.print(r+ " ");
}
}
}
1. HashMap:
HashMap은 Java에서 제공하는 데이터 구조 중 하나로, 키-값 쌍을 저장하는 데 사용됩니다. 이 코드에서는 선수의 이름을 키로, 해당 선수의 인덱스를 값으로 매핑하는데 사용됩니다.
2. solution 메서드:
solution 메서드는 선수 배열과 호출 배열을 인자로 받아서 호출에 따라 선수 배열을 재정렬합니다.
먼저, 선수 배열을 순회하며 각 선수의 이름과 인덱스를 HashMap에 저장합니다.
그런 다음, 호출 배열을 순회하면서 호출된 선수의 인덱스를 찾고, 해당 선수를 이전 선수와 위치를 바꿔서 호출에 따라 재정렬합니다.
재정렬 작업이 끝나면 선수 배열을 반환합니다.
3. main 메서드:
main 메서드는 프로그램의 진입점입니다.
초기 선수 배열과 호출 배열을 생성하고, Solution 클래스의 인스턴스를 만듭니다.
solution 메서드를 호출하여 결과를 얻고, 결과 배열을 출력합니다.