말하는 컴공감자의 텃밭

프로그래머스 달리기 경주 <6점> - 자바(java) HashMap 본문

알고리즘/Programmers - Java

프로그래머스 달리기 경주 <6점> - 자바(java) HashMap

현콩 2023. 5. 20. 15:54
728x90

 

프로그래머스 달리기 경주
2번마~ 4번마~

프로그래머스 달리기 경주

 

callings에 담기면 해당 이름을 가진 선수가 추월했다는 뜻이다. 4등인 "kai"가 불렸다면 3등으로 제쳤다는 말이다.

그럼 calling에 불린 선수와 앞에 있는 선수를 스위칭하면 되는 문제이다.

Map선언으로 선수명과 등수를 Key와 Value로 넣어줬다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.*;
class Solution {
    public String[] solution(String[] players, String[] callings) {
        Map<String,Integer> rmap = new HashMap<>();
        for(int i=0; i<players.length; i++){
            rmap.put(players[i],i);
        }
        
        for(int i = 0; i<callings.length; i++){
        
            int p = rmap.get(callings[i]); //kai 는 [3] = p
            String fp = players[p-1];  //p 에서 -1 위치 인 poe = fp
            
            players[p-1]= callings[i]; // 위치 스위칭 
            players[p] = fp;           // poe <=> kai
            
            rmap.put(callings[i],p-1); // rmap에 정리 
            rmap.put(fp,p);
            
        }
        
        return players;
    }
}
cs

 

진작에 코드 자체에 주석 넣을걸~

 

야미요미

 

 

 

728x90
Comments