[백준] - 20920 영단어 암기는 괴로워 (node.js)

밀루·2025년 1월 21일
1

BOJ

목록 보기
57/82

문제링크

코드

const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
const arr = fs
  .readFileSync(filePath)
  .toString()
  .trim()
  .split("\n")
  .map((line) => line.replace("\r", ""));

const [n, minlong] = arr[0].split(" ").map(Number);

const words = new Map();
for (let i = 1; i <= n; i++) {
  if (arr[i].length >= minlong) words.set(arr[i], (words.get(arr[i]) || 0) + 1);
}

const sortlist = [...words]
  .sort((a, b) => {
    if (b[1] === a[1]) {
      if (b[0].length === a[0].length) return a[0] < b[0] ? -1 : 1;
      return b[0].length - a[0].length;
    }
    return b[1] - a[1];
  })
  .map((el) => el[0])
  .join("\n");

console.log(sortlist);

시간초과가 조금 빡셌던 거 같다............. 처음에 객체를 활용해서 몇개 있는지랑 최소길이 만족하는지 보고 객체 for문 돌려서 그대로 list에 넣어서 sort한 다음에 다시 for문 돌면서 출력하는 식으로 구현했는데.. 이론상 4O(n)도 시간초과가 났다.. 그래서 검색해보니 Map으로 받아서 Map에서 바로 sort해가지고 join("\n")으로 출력하면 시간초과가 안나온다고 해서.. 참고해서 풀었다. Map이랑 별로 안친한데,, ㅋㅎ 앞으로 좀 친해져봐야겠다.

참고링크

profile
이밀루의 도전

0개의 댓글