-
프로그래머스 LV1 - 달리기 경주STUDY/ALGORITHM 2025. 2. 12. 23:29
정말 아무것도 모르던 시절. 이미 한번 도전했던 문제다.
players의 범위도 5<= players <= 50,000 인데다,
callings의 범위도 2<=callings <= 1,000,000 이기 때문에, 아마도 타임아웃에 부딪혔을 수도 있겠다.
이럴 땐 그래도 조금이나마 늘긴 늘었단 생각이 든다. 작성시간까지 해서 10분 정도 걸렸다.
참 아직도 갈 길이 멀다만 그때의 나는 뭐였을까..
아무튼 문제로 돌아가서, 이 문제의 관건은 callings의 값으로 어떻게 플레이어를 빠르게 찾느냐 다.
그래서 배열과 해시로 동시에 관리하기로 한다.
순위가 바뀔때, 배열과 해시를 동시에 갱신해주면, 선수 이름으로 현재 순위를 바로 가져올 수 있고,
그 순위로 배열에 다시 접근 하면 된다.
import java.util.*; class Solution { private Map<String,Integer> currentRankMap; public String[] solution(String[] players, String[] callings) { init(players); for (String call : callings) { int currentRank = currentRankMap.get(call); String passed = players[currentRank - 1]; //지나친 선수 players[currentRank] = passed; // 배열에서 순위 교체 players[currentRank - 1] = call; currentRankMap.put(passed, currentRank); // 해시에서 순위 갱신 currentRankMap.put(call, currentRank - 1); } return players; } // 초기화 private void init(String[] players){ currentRankMap = new HashMap<>(); for (int i = 0; i < players.length; i++) { String player = players[i]; currentRankMap.put(player, i); } } }'STUDY > ALGORITHM' 카테고리의 다른 글
프로그래머스 LV2 - 전화번호 목록 (0) 2025.02.24 프로그래머스 LV1 - 택배 상자 꺼내기 (0) 2025.02.17 프로그래머스 LV1 - 공원 산책 (0) 2025.02.12 프로그래머스 LV1 - 대충 만든 자판 (1) 2025.02.11 프로그래머스 LV2 - 지게차와 크레인 (0) 2025.02.11