https://school.programmers.co.kr/learn/courses/30/lessons/178871
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 풀이
엄청 단순한 문제 같은데 Collection swap이나 평범한 swap 방식으로는 타임 아웃 에러가 발생합니다.
힌트가 map을 이용해서 풀어야한다고 하길래 겨우 풀었습니다.
import java.util.*;
class Solution {
public String[] solution(String[] players, String[] callings) {
Map<String, Integer> playerMap = new HashMap<>();
Map<Integer, String> rankMap = new TreeMap<>();
for (int i = 0; i < players.length; i++) {
playerMap.put(players[i],i+1); rankMap.put(i+1, players[i]);
}
for (String s : callings) {
int tmp = playerMap.get(s); // 추월한 선수
String temp = rankMap.get(tmp-1); // 추월당한 선수
playerMap.put(s, tmp-1); playerMap.put(temp, tmp); // 갱신
rankMap.put(tmp-1, s); rankMap.put(tmp, temp); // 갱신
}
List<String> answer = new ArrayList<>();
for (int key : rankMap.keySet()) answer.add(rankMap.get(key));
return answer.toArray(new String[players.length]);
}
}
rankMap을 TreeMap이 아닌 HashMap으로 해도 되지만 마지막에 한 번 더 정렬해야 해서 TreeMap으로 선언했습니다.
그리고는 딱히 없습니다. 추월 당한 선수와 추월한 선수를 2개의 map에서 계속 업데이트해 주면 됩니다.
괜찮은 문제였습니다. 제 생각에는...
안녕히계세요뿅
'PS' 카테고리의 다른 글
[프로그래머스] 두 큐 합 같게 만들기 자바 풀이 (0) | 2023.04.21 |
---|---|
[프로그래머스] 무인도여행 자바 풀이 (0) | 2023.04.17 |
[프로그래머스] 베스트앨범 자바 풀이 (0) | 2023.04.06 |
[프로그래머스] 방문 길이 자바 풀이 (0) | 2023.04.02 |
[프로그래머스] 오픈채팅방 자바 풀이 (0) | 2023.03.25 |