[프로그래머스] 178871. 달리기 경주

기영·2024년 6월 27일

달리기경주 178871

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

풀이

각 player마다 현재 등수(idx)를 담고있는 HashMap 생성
호명된 선수의 등수(rank)를 확인해 그 전 등수의 player와 교환

코드

import java.util.*;

class Solution {
   public String[] solution(String players[], String[] callings) {
		Map<String, Integer> map = new HashMap<String, Integer>(); // 순위를 저장
       		 
		for(int i = 0 ; i < players.length ; i++) {
			map.put(players[i], i);
		}
		
		for(int i = 0 ; i < callings.length ; i++) {
			int idx = map.get(callings[i]); // 역전한 선수의  위치
            String now = players[idx];		// 역전한 선수
            String prev = players[idx-1];	// 역전당한 선수
            
            players[idx] = prev;
            players[idx-1] = now;
            
            map.put(now, idx-1);
            map.put(prev, idx);
		}
		
		return players;
	}
}
profile
computer engineering student

0개의 댓글