본문 바로가기

컴퓨터/프로그래머스

프로그래머스 - 178871번: 달리기 경주 [Java]

문제: https://school.programmers.co.kr/learn/courses/30/lessons/178871

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

1. 코드

import java.util.*;
class Solution {
    public String[] solution(String[] players, String[] callings) {
        Map <String, Integer> player = new HashMap<>();
        for(int i = 0; i < players.length; i++)
            player.put(players[i], i);
        
        for(String c : callings) {
            int callRank = player.get(c);
            
            String temp = players[callRank];
            players[callRank] = players[callRank - 1];
            players[callRank - 1] = temp;
            
            player.put(c, callRank - 1);
            player.put(players[callRank], callRank);
        }
        return players;
    }
}

2. 설명

Map <String, Integer> player = new HashMap<>();
for(int i = 0; i < players.length; i++)
    player.put(players[i], i);

HashMap에 player의 정보와 등수 정보를 put해줍니다.

for(String c : callings) {
    int callRank = player.get(c);

    String temp = players[callRank];
    players[callRank] = players[callRank - 1];
    players[callRank - 1] = temp;

    player.put(c, callRank - 1);
    player.put(players[callRank], callRank);
}

해설진들이 추월한 선수의 추월 전 등수를 HashMap을 이용하여 callRank에 저장합니다. players의 등수에 맞게 교환합니다. 그리고 변경된 선수들의 순위를 HashMap인 player에도 변경해줍니다.

3. 정리

  1. 인덱스 탐색으로 인한 시간 초과는 HashMap 이용하면 쉽게 해결이 가능하다.
출처: 프로그래머스 코딩 테스트 연습, 
https://school.programmers.co.kr/learn/challenges