Algorithm/백준
백준 1620(나는야 포켓몬 마스터 이다솜)
leecom116
2023. 11. 11. 18:52
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split(" ");
// 도감
int N = Integer.parseInt(s[0]);
// 문제
int M = Integer.parseInt(s[1]);
// String[] arr = new String[N];
HashMap<Integer, String> intMap = new HashMap<>();
HashMap<String, Integer> strMap = new HashMap<>();
for(int i=0; i<N; i++) {
String ss = br.readLine();
intMap.put(i+1, ss);
strMap.put(ss, i+1);
}
// HashMap 이용해서 문제 해결
for(int i=0; i<M; i++) {
String ss = br.readLine();
try {
int num = Integer.parseInt(ss);
System.out.println(intMap.get(num));
} catch(Exception e) {
System.out.println(strMap.get(ss));
}
}
}
}
Review
- 처음에 문제 해결을 했으나 시간 초과 발생
- 배열에 담아 index를 입력 받으면 value 값을 바로 출력했으나, value를 입력 받을 경우 배열 반복문을 한번 더 돌리게 되어 시간 초과
- 처음에 입력받을 때 2개의 해시맵을 만들어 각각 저장한 후 key를 입력 받아 바로 출력