프로그래머스 - 달리기 경주

이상훈·2023년 5월 16일
0

달리기 경주

시간초과 난 내 코드

public class Solution {
    public String[] solution(String[] players, String[] callings) {
        int n = players.length;
        HashMap<String, Integer> indexMap = new HashMap<>();

        for (int i = 0; i < n; i++) {
            indexMap.put(players[i], i);
        }

        for (String calling : callings) {
            int idx = indexMap.get(calling);
            if (idx > 0) {
                String temp = players[idx - 1];
                players[idx - 1] = players[idx];
                players[idx] = temp;

                indexMap.put(players[idx - 1], idx - 1);
                indexMap.put(players[idx], idx);
            }
        }

        return players;
    }
}

정답코드

import java.util.*;

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

풀이


프로그래머스는 확실히 백준과 분위기가 다른것같다.
여태까지 백준만 들여다 봤는데 프로그래머스 문제만 보면 쉽게 풀리지 않는다.
게다가 기업 코테는 프로그래머스에서 많이 보더라 지난 sk코테를 탈탈 털렸다. 구현문제인데...

아무튼 앞으로 프로그래머스를 많이 풀어봐야겠다.
지금까지 본 특징은 자료구조와 배열, 문자열을 굉장히 잘 써야겠다는 느낌이다.

이 문제는 자리바꾸기만 해주면되는 아주 심플한 문제다.
하지만 반복문으로 찾으면 시간초과가 났다.

답은 map으로 푸는것이다.

근데 프로그래머스는 시간제한을 표시를 어디에 하는지 모르겠다..

추가

HashMap<String, String> pairs = new HashMap<>();
pairs.put("key","value");

조회

get
key에 해당하는 value반환
이때 해당 키의 값이 없다면 null반환

pairs.get("key"); //  "value"
pairs.get("strange"); // null

getOrDefault
해당 키 값이 없다면 반환할 값 두번 째 인자에 주기
빈도수 셀 때 유용함

pairs.getOrdefault("strange", "nothing"); // "nothing"

그 외 문법 들

0개의 댓글