1302번: 베스트셀러
첫째 줄에 오늘 하루 동안 팔린 책의 개수 N이 주어진다. 이 값은 1,000보다 작거나 같은 자연수이다. 둘째부터 N개의 줄에 책의 제목이 입력으로 들어온다. 책의 제목의 길이는 50보다 작거나 같고
www.acmicpc.net
핵심 아이디어
카운트 개수에 따라 카운팅하되, 카운트 개수가 같다면 이름의 사전순으로 정렬하는 문제이다.
파이썬으로 하기엔 간편했으나 자바스크립트로 어떻게 2개의 조건을 사용할지,
dict 형을 어떻게 정렬해야할지 고민되었던 문제이다.
먼저 dict는 array타입으로 [키, 값]으로 바꿔주고 그 array에
비교함수를 sort인자로 주어서 해결하였다.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const solution = function (input) {
const n = parseInt(input.shift());
const infomation = {};
for (const row of input) {
if (infomation[row]) {
infomation[row]++;
} else {
infomation[row] = 1;
}
}
const items = Object.keys(infomation).map((key) => [key, infomation[key]]);
items.sort((a, b) => {
if (a[1] > b[1]) return -1;
if (a[1] < b[1]) return 1;
if (a[0] > b[0]) return 1;
if (a[0] < b[0]) return -1;
});
console.log(items[0][0]);
};
const input = [];
rl.on('line', function (line) {
input.push(line);
}).on('close', function () {
solution(input);
process.exit();
});
'개발 > 알고리즘' 카테고리의 다른 글
[LeetCode] 8. String to Integer (atoi) (0) | 2021.01.22 |
---|---|
[Javascript][LeetCode] Reverse Integer (0) | 2021.01.17 |
[Javascript][BOJ] 1967 트리의 지름 (0) | 2021.01.11 |
[Javascript][BOJ] 1446 지름길 (0) | 2021.01.10 |
[Javascript][BOJ] 1504 특정한 최단 경로 (0) | 2021.01.08 |