신입사원 무지는 게시판 불량 이용자를 신고하고 처리 결과를 메일로 발송하는 시스템을 개발하려 합니다. 무지가 개발하려는 시스템은 다음과 같습니다.
이용자의 ID가 담긴 문자열 배열 id_list, 각 이용자가 신고한 이용자의 ID 정보가 담긴 문자열 배열 report, 정지 기준이 되는 신고 횟수 k가 매개변수로 주어질 때, 각 유저별로 처리 결과 메일을 받은 횟수를 배열에 담아 return 하도록 solution 함수를 완성해주세요.
function solution(id_list, report, k) {
const newReport = [...new Set(report)].map((el) => el.split(" "));
const result = id_list.map((el) => {
email = 0;
for (let i = 0; i < newReport.length; i++) {
if (el === newReport[i][0]) {
const num = newReport.filter((el) => el[1] === newReport[i][1]).length;
if (num >= k) {
email++;
}
}
}
return email;
});
return result;
}
여러 곳에서 시간 초과가 나는 코드였다.
문제는 newReport 반복문 안에서, 신고한 이용자를 찾을 때마다 신고당한 이용자가 몇번의 신고를 당했는지를 filter로 가져오기 때문에, 같은 코드가 굉장히 많이 실행이 된다. 때문에 시간 초과로 실패한 테스트 케이스가 많았고, 다른 풀이를 생각했다.
function solution(id_list, report, k) {
const newReport = [...new Set(report)].map((el) => el.split(" "));
let reportNum = {};
newReport.forEach((el) => {
if (!reportNum[el[1]]) {
reportNum[el[1]] = 1;
} else if (reportNum[el[1]]) {
reportNum[el[1]] += 1;
}
});
const result = id_list.map((el) => {
email = 0;
for (let i = 0; i < newReport.length; i++) {
if (el === newReport[i][0] && reportNum[newReport[i][1]] >= k) {
email++;
}
}
return email;
});
return result;
}
reportNum이라는 객체를 만들어서, 신고당한 이용자가 몇 번 신고당했는지를 알 수 있도록 제작했다. 그리하여 아까 진행했던 newReport 반복문 안에서도 reportNum 안에서 k보다 큰지 여부만 체크하여 코드를 쓸데없이 재실행하는 일이 없어졌다. 이렇게 문제가 해결되었다.