TIL

프로그래머스 알고리즘 문제풀이 달리기 경주 (시간 초과)

everyday-spring 2024. 8. 28. 15:59

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

 

프로그래머스

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

programmers.co.kr

 

처음 작성한 코드

import java.util.*;

class Solution {
    public String[] solution(String[] players, String[] callings) {
        List<String> list = Arrays.asList(players);
        
        for(String calling : callings) {
            int index = list.indexOf(calling);
            
            players[index] = players[index - 1];
            players[index - 1] = calling;
        }
        
        
        return players;
    }
}

문제점 : List를 사용해서 인덱스 검색시간이 오래걸림

 

수정된 코드

import java.util.*;

class Solution {
    public String[] solution(String[] players, String[] callings) {
        HashMap<String, Integer> map = new HashMap<>();
        
        for(int i = 0; i < players.length; i++) {
            map.put(players[i], i);
        }
        
        for(String  calling : callings) {
            int index = map.get(calling);
            
            players[index] = players[index - 1];
            players[index - 1] = calling;
            
            map.put(players[index - 1], index - 1);
            map.put(players[index], index);
        }
        
        
        return players;
    }
}

해결방안 : HashMap을 사용하여 검색 시간을 단축시켰다