💡 나의 답
package baekjoon.Bronze3.Day250113;
import java.util.Scanner;
public class BOJ2776 {
// 암기왕
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i=0; i<T; i++) {
int N = sc.nextInt();
int[] note1 = new int[N];
for (int j=0; j<note1.length; j++) {
note1[j] = sc.nextInt();
}
int M = sc.nextInt();
for (int j=0; j<M; j++) {
boolean found = false;
int temp = sc.nextInt();
for (int k=0; k<note1.length; k++) {
if (note1[k]==temp) found = true;
}
if (found) System.out.println(1);
else System.out.println(0);
}
}
}
}
💡 개선 답
package baekjoon.Bronze3.Day250113;
import java.util.HashSet;
import java.util.Scanner;
public class BOJ2776 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int N = sc.nextInt();
HashSet<Integer> note1 = new HashSet<>();
for (int j = 0; j < N; j++) {
note1.add(sc.nextInt());
}
int M = sc.nextInt();
StringBuilder result = new StringBuilder();
for (int j = 0; j < M; j++) {
int num = sc.nextInt();
if (note1.contains(num)) {
result.append(1).append("\n");
} else {
result.append(0).append("\n");
}
}
System.out.print(result);
}
}
}
💡 추가 학습 개념
⚽ HashSet
HashSet이란?
- 특정 요소의 존재 여부를 빠르게 확인할 수 있다.
HashSet을 사용하는 이유
- 배열을 순차 탐색하는 대신, HashSet의 빠른 탐색 성능을 활용하여 실행 속도를 대폭 줄일 수 있다.
- HashSet은 정렬이 필요 없는 경우나 데이터의 중복을 제거하고 싶을 때 유용하다.
HashSet 주요 메서드
- add(E e): 요소 추가
- contains(Object o): 특정 요소가 있는지 확인
- remove(Object o): 요소 제거.
- clear(): 모든 요소를 제거
⚽ StringBuilder
StringBuilder란?
- 문자열을 다룰 때 String은 불변 객체로, 수정할 때마다 새로운 객체가 생성된다.
- StringBuilder는 가변 객체로, 문자열을 수정할 때 추가 메모리 할당 없이 효율적으로 처리할 수 있다.
StringBuilder를 사용하는 이유
- System.out.println을 반복적으로 호출하면 출력 속도가 느려질 수 있다.
- StringBuilder에 결과를 누적한 뒤 한 번에 출력하면 성능이 크게 향상된다.
StringBuilder 주요 메서드
- append(String s): 문자열 추가
- toString(): 누적된 문자열 반환
- setLength(int newLength): 문자열 길이 조정
'컴퓨터 프로그래밍 > 알고리즘' 카테고리의 다른 글
[알고리즘] Baekjoon Bronze 2,3 (0) | 2025.01.30 |
---|---|
[알고리즘] 이진 탐색 (Binary Search) (0) | 2025.01.14 |
[알고리즘] Baekjoon Bronze 4 (1) | 2025.01.10 |
[알고리즘] Baekjoon Bronze 5 (0) | 2025.01.10 |
[알고리즘] 배열 (0) | 2024.10.07 |