본문 바로가기
개발 노트/백준, 프로그래머스 풀이

[백준 1822/javascript] 차집합

by tokkiC 2022. 9. 12.

for문으로 완전탐색하였더니 탐색수가 너무 많아 몇번이나 시간초과가 걸려서 완전탐색 로직을 버리고 다시 풀었다

탐색할 배열을 set 으로 만들고 set 의 delete 를 사용하여 중복되는 것을 제거

남는 것을 배열로 다시 만들어 정렬해주면 되는 문제였다

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

 

1822번: 차집합

첫째 줄에는 집합 A의 원소의 개수 n(A)와 집합 B의 원소의 개수 n(B)가 빈 칸을 사이에 두고 주어진다. (1 ≤ n(A), n(B) ≤ 500,000)이 주어진다. 둘째 줄에는 집합 A의 원소가, 셋째 줄에는 집합 B의 원소

www.acmicpc.net

let input = [];

const readline = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
});

readline.on("line", (line) => {
  input.push(line);
});

readline.on("close", () => {
  solution(input);
  process.exit();
});

const solution = (inp) => {
  inp.shift();
  let a = inp
    .shift()
    .split(" ")
    .map((el) => Number(el));
  let b = inp
    .shift()
    .split(" ")
    .map((el) => Number(el));
  let set = new Set(a);
  for (el of b) {
    set.delete(el);
  }
  if (set.size === 0) {
    console.log(0);
  } else {
    let arr = Array.from(set);
    let ans = arr.sort((a, b) => a - b);
    console.log(ans.length);
    console.log(ans.join(" "));
  }
};

댓글