보라코딩

프로그래머스 자바 :: 달리기경주 (1단계) 본문

프로그래머스 (java)

프로그래머스 자바 :: 달리기경주 (1단계)

new 보라 2024. 5. 22. 20:11

비교적 풀만한 문제였다!

그래도 저번에 map 문제 풀어봤다고 바로 떠올랐다.

 

다만 시간초과가 떠서 난감했는데

 

if 조건도 추가해주고

map을 무조건 다 변경해주는 것이 아니라

필요한 것만 업데이트하게 해서 해결했다.

 

 

 

 

 

import java.util.*;

class Solution {
    public String[] solution(String[] players, String[] callings) {
        //String[] answer = {};
        HashMap<String, Integer> map = new HashMap<>();
        
        for (int i = 0; i < players.length; i++) {
            map.put(players[i], i);
        }
        
        for (String calling : callings) {
            int currentPosition = map.get(calling);
            
            // 시간 초과 문제 때문에 추가함
            if (currentPosition > 0) {
                String frontPlayer = players[currentPosition - 1];
                
                // swap
                players[currentPosition] = frontPlayer;
                players[currentPosition - 1] = calling;

                // map도 변경 시켜줘야함!!
                map.put(calling, currentPosition -1);
                map.put(frontPlayer, currentPosition);

            } 
        }
        return players;
    }
}