[프로그래머스(Programmers)][Java,Python] (Lv1) 달리기 경주

728x90

 

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

1. Java

import java.util.*;
class Solution {
    public String[] solution(String[] players, String[] callings) {
        String[] answer = new String[players.length];
        HashMap<String,Integer> players_info = new HashMap<>();
        for ( int i = 0; i < players.length; ++i ) {
            players_info.put(players[i], i);
            answer[i] = players[i];
        }
        for ( String calling : callings ) {
            int idx_win = players_info.get(calling);
            int idx_lose = idx_win - 1;
            String nm_win = calling;
            String nm_lose = answer[idx_lose];
            answer[idx_win] = nm_lose;
            answer[idx_lose] = nm_win;
            players_info.put(nm_win, idx_lose);
            players_info.put(nm_lose, idx_win);
        }
        return answer;
    }
}
더보기
import java.util.*;
class Solution {
    public String[] solution(String[] players, String[] callings) {
        String[] answer = {};
        List<String> players_list = new LinkedList<>();
        for ( String player : players ) {
            players_list.add(player);
        }
        for ( String calling : callings ) {
            int idx = players_list.indexOf(calling);
            players_list.add(idx - 1, players_list.remove(idx));
        }
        answer = new String[players_list.size()];
        for ( int i = 0; i < players_list.size(); ++i ) {
            answer[i] = players_list.get(i);
        }
        return answer;
    }
}

// 시간 초과

 

2. Python

def solution(players, callings):
    answer = []
    players_info = {}
    for i in range(len(players)) :
        players_info[players[i]] = i
        answer.append(players[i])
    for calling in callings :
        idx_win = players_info[calling]
        idx_lose = idx_win - 1
        nm_win = calling
        nm_lose = answer[idx_lose]
        answer[idx_win] = nm_lose
        answer[idx_lose] = nm_win
        players_info.update({nm_win: idx_lose})
        players_info.update({nm_lose: idx_win})
    return answer

 

반응형