백준 - 숫자카드 2[java]

스브코·2021년 10월 29일

문제 설명

입력
첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다.

셋째 줄에는 M(1 ≤ M ≤ 500,000)이 주어진다. 넷째 줄에는 상근이가 몇 개 가지고 있는 숫자 카드인지 구해야 할 M개의 정수가 주어지며, 이 수는 공백으로 구분되어져 있다. 이 수도 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다.

출력
첫째 줄에 입력으로 주어진 M개의 수에 대해서, 각 수가 적힌 숫자 카드를 상근이가 몇 개 가지고 있는지를 공백으로 구분해 출력한다.

예제 입력 1
10
6 3 2 10 10 10 -10 -10 7 3
8
10 9 -5 2 3 4 5 -10

예제 출력 1
3 0 0 1 2 0 0 2

문제 풀이

둘째 줄에 입력된 숫자들이 각각의 카드이고, 넷째줄에 입력된 숫자들이 카드 리스트 이다.

카드리스트에 있는 카드들이 둘째 줄에 나열된 카드들을 보고 몇개씩 나왔는지 리턴하면 되는 문제이다.

시간 초과 코드

import java.util.HashMap;
import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        HashMap<Integer, Integer> hs = new HashMap<>();
        int cardNum = sc.nextInt();
        sc.nextLine();
        for(int i = 0; i < cardNum; i++) {
            int card = sc.nextInt();
            if(!hs.containsKey(card))
                hs.put(card, 1);
            else {
                int update = hs.get(card) + 1;
                hs.put(card, update);
            }
        }
        sc.nextLine();
        int total = sc.nextInt();
        sc.nextLine();
        for(int i = 0; i < total; i++) {
            int card = sc.nextInt();
            if(!hs.containsKey(card))
                System.out.print(0 + " ");
            else
                System.out.print(hs.get(card + " "));
        }
    }
}

제한시간이 1초라서 시간초과로 실패 했다.

통과 코드

import java.util.HashMap;
import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        HashMap<Integer, Integer> hs = new HashMap<>();
        int cardNum = sc.nextInt();
        sc.nextLine();
        for(int i = 0; i < cardNum; i++) {
            int card = sc.nextInt();
            if(!hs.containsKey(card))
                hs.put(card, 1);
            else {
                int update = hs.get(card) + 1;
                hs.put(card, update);
            }
        }
        sc.nextLine();
        int total = sc.nextInt();
        sc.nextLine();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < total; i++) {
            int card = sc.nextInt();
            if(!hs.containsKey(card)) {
                sb.append(0);
                sb.append(" ");
            } else {
                sb.append(hs.get(card));
                sb.append(" ");
            }
        }
        System.out.println(sb.toString().substring(0, sb.toString().length() - 1));
    }
}

StringBuilder를 사용해 속도 향상을 시켜주니 통과 되었다.

profile
익히는 속도가 까먹는 속도를 추월하는 그날까지...

0개의 댓글