본문 바로가기
Algorithm

백준 10816번 :: 숫자 카드 2

by DaSsom 2023. 6. 23.

음악 들으면서 대충 끄적임

import java.io.*;
import java.util.StringTokenizer;

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));

        int N = Integer.parseInt(br.readLine());
        int[] hasCard = new int[N];

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

        int M = Integer.parseInt(br.readLine());
        int[] questionCard = new int[M];
        StringTokenizer st2 = new StringTokenizer(br.readLine());
        for (int i = 0; i < M; i++) {
            questionCard[i] = Integer.parseInt(st2.nextToken());
        }

        int[] ans = new int[questionCard.length];
        for (int num : hasCard) {
            for (int i = 0; i < questionCard.length; i++) {
                if (num == questionCard[i]) {
                    ans[i]++;
                }
            }
        }

        for (int num : ans) {
            bw.write(num + " ");
        }

        bw.flush();
        bw.close();
    }
}

 

 

 

역시 ^^ 시간초과 예상했음 중첩 반복문에.. 그냥 생각이란걸 안하고 대충 풀었기 때문에...

그래서 조금 더 개선을 해보기 위해 Map을 써봤다. 

 

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

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));

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

        Map<Integer, Integer> cardCount = new HashMap<>();
        for (int i = 0; i < N; i++) {
            int card = Integer.parseInt(st.nextToken());
            cardCount.put(card, cardCount.getOrDefault(card, 0) + 1);
        }

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

        int[] ans = new int[M];
        for (int i = 0; i < M; i++) {
            int question = Integer.parseInt(st2.nextToken());
            ans[i] = cardCount.getOrDefault(question, 0);
        }

        for (int num : ans) {
            bw.write(num + " ");
        }

        bw.flush();
        bw.close();
    }
}

 

 

이 정도면.. 개선이 되었다고 봐도 될런지 머르겠따