728x90
문제
숫자 카드는 정수 하나가 적혀져 있는 카드이다. 상근이는 숫자 카드 N개를 가지고 있다. 정수 M개가 주어졌을 때, 이 수가 적혀있는 숫자 카드를 상근이가 가지고 있는지 아닌지를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 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을, 아니면 0을 공백으로 구분해 출력한다.
두 가지 방법을 활용하여 풀었다.
먼저 HashSet의 contains 메소드를 이용하여 포함 여부를 검사하는 방법이다.
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < N; i++)
set.add(sc.nextInt());
int M = sc.nextInt();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < M; i++) {
if (set.contains(sc.nextInt()))
sb.append(1).append(" ");
else
sb.append(0).append(" ");
}
System.out.println(sb.toString());
}
}
그리고 count 배열을 활용해서 해당 배열의 index가 1인지 0인지 검사하는 것이다.
음수가 입력될 수 있기 때문에 음수 범위 중 가장 작은 값을 더해서 count 배열에 담았다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
StringTokenizer input = new StringTokenizer(br.readLine());
int[] arr = new int[20000001];
for (int i = 0; i < N; i++)
arr[Integer.parseInt(input.nextToken()) + 10000000]++;
int M = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < M; i++) {
int k = Integer.parseInt(st.nextToken());
sb.append(arr[k + 10000000]).append(" ");
}
System.out.println(sb.toString());
}
}
728x90
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 1004 - 어린 왕자 (자바/Java) (0) | 2022.08.25 |
---|---|
[백준] 1764 - 듣보잡 (0) | 2022.08.25 |
[백준] 4256 - 트리 (자바/Java) (1) | 2022.08.25 |
[백준] 1991 - 트리 순회 (0) | 2022.08.24 |
[백준] 1182 - 부분수열의 합 (자바/Java) 재귀 부분집합 (0) | 2022.08.24 |