Baekjun number 10816, number card 2 (with.Java)
This article explores Baekjoon Problem 10816, Number Card 2 (with Java).
We will learn by solving coding test problems, reflecting on previous problems, and exploring different solution methods.
Let’s first look at the problem.
Problem
A number card is a card with a single integer written on it.
Sanggeun has N number cards.
Given M integers, write a program that calculates how many number cards Sanggeun has.
Input
The first line contains the number N of number cards Sanggeun has (1 ≤ N ≤ 500,000).
The second line contains the integers written on the number cards.
The numbers written on the number cards are greater than or equal to -10,000,000 and less than or equal to 10,000,000.
The third line contains M (1 ≤ M ≤ 500,000).
The fourth line contains M integers, separated by spaces, for which the number cards Sanggeun has to be calculated.
This number is greater than or equal to -10,000,000 and less than or equal to 10,000,000.
Output
For the M numbers given in the first line of input, print the number of cards Sanggeun has, separated by spaces.
Problem Solution
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.valueOf(br.readLine());
String[] cards = br.readLine().split(" ");
HashMap<String, Integer> map = new HashMap<>();
for(int i = 0; i < N; i++){
map.put(cards[i], map.getOrDefault(cards[i], 0) + 1);
}
int M = Integer.valueOf(br.readLine());
String[] check = br.readLine().split(" ");
br.close();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < M; i++){
sb.append(map.getOrDefault(check[i], 0)).append(" ");
}
System.out.print(sb);
}
}
Solution explanation
First, we read the input using BufferedReader.
The first input line represents the number of cards, N, and the second is an array of strings representing the card numbers.
This stores the card numbers in a HashMap. The HashMap records the number of times each number appears.
The code map.put(cards[i], map.getOrDefault(cards[i], 0) + 1) increments the value by 1 if the number already exists in the map. Otherwise, it sets the default value to 0 and initializes it to 1.
The third input line represents the number of numbers to check, M, and the fourth is an array of numbers to check.
We check how many times each number appears in the HashMap and store the result in a StringBuilder.
map.getOrDefault(check[i], 0) returns the value if the number exists in the map, or 0 if it doesn’t.
Finally, we output the result stored in the StringBuilder.
This allows us to efficiently output the number of times each number appears.