코딩테스트/프로그래머스

[Java] 프로그래머스 level1 - 달리기 경주

곰돌이볼 2023. 7. 27. 16:04

문제


 

코드


  • 로직 1)
    • 선수 이름으로 조회하는 map과 순위로 조회하는 map을 선언해서 문제 해결
import java.util.*;

class Solution {
    public String[] solution(String[] players, String[] callings) {
        String[] answer = players.clone();
        Map<String, Integer> names = new HashMap<>();
        Map<Integer, String> counts = new HashMap<>();
        
        // map 초기화
        for(int i=0; i<answer.length; i++) {
            names.put(answer[i], i);
            counts.put(i, answer[i]);
        }
        
        // callings를 이용해서 경주가 끝난 후 선수의 순위 구하기
        String tmp;
        Integer count;
        for(String name : callings) {
            count = names.get(name); // 역전하기 전 순위
            tmp = counts.get(count-1); // 역전당한 선수의 이름
            
            // 역전된 상황에 맞추어 값 변경하기
            names.replace(name, count-1);
            names.replace(tmp, count);
            counts.replace(count, tmp);
            counts.replace(count-1, name);
        }
        
        // answer 구하기
        for(int i=0; i<answer.length; i++) {
            answer[i] = counts.get(i);
        }
        
        return answer;
    }
}

 

주의할 점 & 통과여부


  • 주의할 점
    • 배열과 이중 for문을 이용해서 문제를 해결할 경우, 시간 초과 문제 발생
    • 24행에서 count값을 (count-1)로 두어서 문제해결에 애를 먹음

 

  •  결과
    • 통과