코딩테스트 연습 기록

이종길·2022년 2월 21일
0

코딩테스트 연습

목록 보기
81/128

2022.02.21 58일차

백준 10816번 (숫자 카드 2)

문제

숫자 카드는 정수 하나가 적혀져 있는 카드이다. 상근이는 숫자 카드 N개를 가지고 있다. 정수 M개가 주어졌을 때, 이 수가 적혀있는 숫자 카드를 상근이가 몇 개 가지고 있는지 구하는 프로그램을 작성하시오.

나의 풀이

  1. 숫자 카드 개수 N, 가지고 있는 숫자 카드 개수 M
  2. Map 활용(키 - 숫자, 값 - 개수)
  3. 출력 단계에서 가지고 있으면 값 출력, 아니면 0 출력
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int N = Integer.parseInt(st.nextToken());
        Map<Integer, Integer> map = new HashMap<>();

        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < N; i++) {
            int temp = Integer.parseInt(st.nextToken());

            if (map.containsKey(temp)) {
                map.put(temp, map.get(temp) + 1);
            } else {
                map.put(temp, 1);
            }
        }

        int M = Integer.parseInt(br.readLine());
        st = new StringTokenizer(br.readLine());

        for (int x = 0; x < M; x++) {
            int temp = Integer.parseInt(st.nextToken());
            bw.write(map.getOrDefault(temp, 0) + " ");
        }
        bw.close();
    }
}

생각하기

  • BufferedWriter -> Int출력x
  • Map -> getOrDefault 생각하기
profile
Go High

0개의 댓글

관련 채용 정보