본문 바로가기

Coding Test/프로그래머스 연습

[JAVA] 달리기 경주

문제 설명

얀에서는 매년 달리기 경주가 열립니다. 해설진들은 선수들이 자기 바로 앞의 선수를 추월할 때 추월한 선수의 이름을 부릅니다. 예를 들어 1등부터 3등까지 "mumu", "soe", "poe" 선수들이 순서대로 달리고 있을 때, 해설진이 "soe"선수를 불렀다면 2등인 "soe" 선수가 1등인 "mumu" 선수를 추월했다는 것입니다. 즉 "soe" 선수가 1등, "mumu" 선수가 2등으로 바뀝니다.
선수들의 이름이 1등부터 현재 등수 순서대로 담긴 문자열 배열 players와 해설진이 부른 이름을 담은 문자열 배열 callings가 매개변수로 주어질 때, 경주가 끝났을 때 선수들의 이름을 1등부터 등수 순서대로 배열에 담아 return 하는 solution 함수를 완성해주세요.

 

👽내 코드

class Solution {
    public String[] solution(String[] players, String[] callings) {
        String loser = "";
        
        for(int i=0; i < callings.length; i++){
            for(int j=0; j < players.length; j++){
                if(players[j].equals(callings[i])){
                    loser = players[j-1];
                    players[j-1]= players[j];
                    players[j] = loser;                    
                }
            }
        }
        return players;
    }
}

 

이렇게풀면, 시간초과 하는 테스트 예시들이 있었다.

아마 제한사항 때문에, idx가 커질수록 중첩되는 for문이 계속 늘어나서 시스템 과부하가 걸리는 것 같다. 

이렇게 모든  케이스를 순회하지 않고 바로 1:1 swap 해주는 방식을 찾음

>> HashMap

 

 

다시 생각한 풀이

import java.util.*;

class Solution {
    public String[] solution(String[] players, String[] callings) {
        
        HashMap<String,Integer> mapP = new HashMap<>();
        HashMap<Integer,String> mapR = new HashMap<>();
        
        String loser = "";
        int rank = 0;
        for(int i=0; i < players.length; i++){
            mapP.put(players[i],i);
            mapR.put(i,players[i]);
        }
        
        for(int j=0; j < callings.length; j++){
            rank = mapP.get(callings[j]);
            loser = mapR.get(rank-1);
            mapR.put(rank,loser);
            mapR.put(rank-1,callings[j]);
            mapP.put(loser,rank);
            mapP.put(callings[j],rank-1);
        }
        
        //map을 배열에 채워넣기
        for(int i=0; i < players.length; i++){
            players[i] = mapR.get(i);
        }
        return players;
    }
}

 

바꿔주는 건 비슷하다.

 

1. <이름,순위><순위,이름> 형태의 제네릭을 가지는 해쉬맵 2개 생성

원래는 <이름 ,순위>만 만들려고 했더니 value값만 가져와녀서 이름을 가져올 수가 없었음

 

2. 바꾸는건 어렵지 않았는데 배열에 mapR(랭크넣고 이름나오는)만 필요하다고 생각해서 

mapP를 swap해주지 않았더니 제대로 업데이트 되지 않았다.

저기도 for문의 일부인데 왜 업뎃이 필요없다고 생각했는지 바보같다.

 

HashMap을 사용하면 1:1로 데이터를 넣을 수 있기때문에 데이터를 효율적으로 수정 가능.

 

🌈다른 풀이

import java.util.HashMap;

public class Solution {
    public String[] solution(String[] players, String[] callings) {
        int n = players.length;
        HashMap<String, Integer> indexMap = new HashMap<>();

        for (int i = 0; i < n; i++) {
            indexMap.put(players[i], i);
        }

        for (String calling : callings) {
            int idx = indexMap.get(calling);
            if (idx > 0) {
                String temp = players[idx - 1];
                players[idx - 1] = players[idx];
                players[idx] = temp;

                indexMap.put(players[idx - 1], idx - 1);
                indexMap.put(players[idx], idx);
            }
        }

        return players;
    }
}

 

내가 처음 생각했던 거에서 두번째 for문 대신 해쉬맵에 넣은 값을 뺐으면 바로 저렇게 바꿀 수 있는데....

뭔가 난 더 어렵게 해쉬맵 자체를 수정하여 배열에 넣고......

이게  더 효율적인 것 같다.