백준 - 10816 - 숫자 카드2
2021. 3. 29. 22:43ㆍAlgorithm
10816번: 숫자 카드 2
첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,
www.acmicpc.net
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class 숫자_카드_2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
sc.nextLine();
String[] cards = sc.nextLine().split(" ");
sc.nextLine();
String[] numbers = sc.nextLine().split(" ");
Map<String, Integer> map = new HashMap<>();
for(int i=0; i<cards.length; i++) {
map.put(cards[i], map.get(cards[i]) == null ? 1 : map.get(cards[i]) + 1);
}
StringBuilder result = new StringBuilder();
for(int i=0; i<numbers.length; i++) {
result.append((map.get(numbers[i]) == null ? 0 : map.get(numbers[i])) + " ");
}
System.out.println(result.toString().trim());
}
}
|
cs |
알고리즘
- 해싱
- 해싱을 이용해 O(n^2)을 O(n)으로 풀어야 하는 문제.
- 해쉬맵을 이용하여 카드의 갯수를 저장하고 숫자에 맞는 카드수를 해쉬맵에서 가져오면 된다.
'Algorithm' 카테고리의 다른 글
백준 - 16926 - 배열 돌리기1 (0) | 2021.04.07 |
---|---|
백준 - 2776 - 암기왕 (0) | 2021.03.30 |
프로그래머스 - 그래프 - 가장 먼 노드 (0) | 2021.03.29 |
백준 - 13913 - 숨바꼭질4 (0) | 2021.03.27 |
백준 - 13549 - 숨바꼭질3 (0) | 2021.03.27 |