코코드드카카타타
뭐지 너무 간단한거 아닌가
import java.util.ArrayList;
import java.util.List;
class Solution {
public String[] solution(String[] players, String[] callings) {
ArrayList<String> answer = new ArrayList<>(List.of(players));
String temp;
for(String call: callings) {
int i = answer.indexOf(call);
temp = answer.get(i - 1);
answer.set(i - 1, call);
answer.set(i, temp);
}
return answer.toArray(new String[0]);
}
}
역시나 시간초과로 몇몇 테스트케이스에서 실패가 반환되었다
Arraylist의 indexOf 메서드를 사용하면 리스트를 처음부터 끝까지 순회하기 때문에 오래 걸린다
HashMap 이용
import java.util.HashMap;
import java.util.Map;
class Solution {
public String[] solution(String[] players, String[] callings) {
Map<String, Integer> playerIndex = new HashMap<>();
for (int i = 0; i < players.length; i++) {
playerIndex.put(players[i], i);
}
for (String call : callings) {
int currentIndex = playerIndex.get(call);
int previous = currentIndex -1;
String previousPlayer = players[previous];
players[previous] = call;
players[currentIndex] = previousPlayer;
playerIndex.put(call, previous);
playerIndex.put(previousPlayer, currentIndex);
}
return players;
}
}
각 플레이어들의 위치를 저장하는 hashmap playerIndex를 이용해서 인덱스와 플레이어를 빨리 찾아서 이용할 수 있었다