요약
풀이 시간 : 23분 14초
풀이
1. 중복 제거
2. 데이터 매핑
다름 사람 풀이를 참고한 리펙토링
1. 중복의 대상을 명확히 하기, -> report에서 target 만 중복처리해서 추가 로직생김
2. || 연산자 활용, -> map.set(id , (map.get(id) || 0) + 1);
문제 링크
[프로그래머스]-신고 결과 받기
풀이
function solution(id_list, report, k) {
const reportMailCounts = new Map(id_list.map((id) => [id, 0]));
const reportMap = new Map(id_list.map((id) => [id, new Set()]));
const stopMap = new Map();
for (const rep of report) {
const [id, target] = rep.split(' ');
reportMap.get(id).add(target);
}
for (const targets of reportMap.values()) {
for (const id of [...targets]) {
if (stopMap.has(id)) {
stopMap.set(id, stopMap.get(id) + 1);
} else {
stopMap.set(id, 1);
}
}
}
for (const [id, targets] of reportMap) {
for (const target of [...targets]) {
if (stopMap.get(target) >= k) {
reportMailCounts.set(id, reportMailCounts.get(id) + 1);
}
}
}
return [...reportMailCounts.values()];
}
다른 사람 풀이
function solution(id_list, report, k) {
let reports = [...new Set(report)].map(a=>{return a.split(' ')});
let counts = new Map();
for (const bad of reports){
counts.set(bad[1],counts.get(bad[1])+1||1)
}
let good = new Map();
for(const report of reports){
if(counts.get(report[1])>=k){
good.set(report[0],good.get(report[0])+1||1)
}
}
let answer = id_list.map(a=>good.get(a)||0)
return answer;
}
코드 리펙토링
function solution(id_list, report, k) {
const uniqueReports = [...new Set(report)].map((rep) => rep.split(' '));
const reportCounts = new Map();
for (const [_, target] of uniqueReports){
reportCounts.set(target, (reportCounts.get(target) || 0) + 1);
}
const resultMailCounts = new Map(id_list.map((id) => [id, 0]));
for (const [reporter, target] of uniqueReports) {
if (reportCounts.get(target) >= k) {
resultMailCounts.set(reporter, resultMailCounts.get(reporter) + 1);
}
};
return id_list.map((id) => resultMailCounts.get(id));
}