알고리즘/백준

10816번 - 숫자 카드 2

fleur75 2023. 6. 6. 12:49
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;

public class Main {
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		HashMap<Integer, Integer> map = new HashMap<>();
		int N = Integer.parseInt(br.readLine());
		int input;
		StringTokenizer st = new StringTokenizer(br.readLine());
		for(int i=0;i<N;i++) {
			input = Integer.parseInt(st.nextToken());
			if(map.containsKey(input)) {
				map.put(input, map.get(input)+1);
			} else {
				map.put(input, 1);
			}
		}
		int M = Integer.parseInt(br.readLine());
		st = new StringTokenizer(br.readLine());
		for(int i=0;i<M;i++) {
			input = Integer.parseInt(st.nextToken());
			sb.append(map.containsKey(input) ? map.get(input)+" " : 0+" ");
		}
		System.out.println(sb);
		br.close();
	}
}

가장 먼저 브루트포스를 떠올리기 쉽지만 매 번 전체를 탐색해야 하기 때문에 시간적으로 불가능합니다.

 

이 때 문제의 요구사항을 살펴보면 결국 리스트에 해당 숫자가 몇 번 나타나는지 '검색'하는 것이 목적임을 알 수 있습니다.

따라서 데이터를 저장할 때 HashMap을 이용해서 해당 숫자가 입력될 때 마다 value가 1씩 늘어나는 식으로 처리하여 탐색하지 않고도 검색을 처리하게 만들 수 있습니다.

 

StringBuilder를 이용해 실행시간을 줄이는 작업도 필수적입니다.