백준 1822 - 차집합

백준 1822 - 차집합

https://www.acmicpc.net/problem/1822

★ 풀이

간단한 문제로 HashMap 또는 HashSet을 사용하면 풀 수 있다. 단순히 주어진 값들을 넣고 중복된 내용을 찾아 제거하면 된다. 그런데 문제에서 요구하는 것은 증가하는 순서대로 출력하라는 것이다. 하지만 HashMap이나 HashSet은 비선형 자료구조이다. 즉, 순서를 보장하지 않는다는 말이다. 그럼 HashMap과 HashSet은 사용하지 못하는 것일까?

이럴때 사용하는 것이 linkedHashSet, linkedHashMap 이다. 비선형 자료구조에 선형 자료구조의 속성을 부여하는 것이다. 이러면 넣을 때와 꺼낼 때의 순서가 보장되므로 쉽게 구현할 수 있다.

★ 소스 코드

import java.io.*; import java.util.*; // 좋은 스킬 흡수하기 public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static Set hs; public static void main(String[] args) throws IOException { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); hs = new LinkedHashSet<>(); // 순서 보장 int a[] = new int[n]; int b[] = new int[m]; st = new StringTokenizer(br.readLine()); for(int i = 0; i

"); for(int x : hs) { sb.append(x).append(" "); } System.out.println(sb.toString()); } }

from http://sweet-smell.tistory.com/158 by ccl(A) rewrite - 2021-12-10 14:27:48