백준 - 1620번(나는야 포켓몬 마스터 이다솜)

최지홍·2022년 2월 14일
0

백준

목록 보기
58/145

문제 출처: https://www.acmicpc.net/problem/1620


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
        int N = Integer.parseInt(tokenizer.nextToken()); // N개의 포켓몬
        int M = Integer.parseInt(tokenizer.nextToken()); // M개의 문제

        StringBuilder sb = new StringBuilder();

        HashMap<Integer, String> indexMap = new HashMap<>();
        HashMap<String, Integer> stringMap = new HashMap<>();

        int index = 1;

        while (N-- > 0) {
            String temp = reader.readLine();
            indexMap.put(index, temp);
            stringMap.put(temp, index++);
        }

        for (int i = 0; i < M; i++) {
            String temp = reader.readLine();
            if (stringMap.containsKey(temp)) sb.append(stringMap.get(temp));
            else sb.append(indexMap.get(Integer.parseInt(temp)));
            sb.append("\n");
        }

        System.out.println(sb);
    }

}

  • 처음에 하나의 HashMap을 사용하여 키 검색, 값 검색으로 문제를 풀었으나 시간초과가 떴다.
  • 이에 HashMap을 2개 사용하여 이름으로 검색하는 것과 번호로 검색하는 것 모두 HashMap의 put() 메서드로 가져올 수 있게 하였다.
profile
백엔드 개발자가 되자!

0개의 댓글