프로그래머스
문제를 풀때 배열을 사용하면 반복문으로 원하는 데이터를 찾기까지 최악의 경우 O(N)이 걸리므로 배열의 사용을 지양하고 객체를 사용했다. 하지만 반복문을 많이 사용하다보니 테스트케이스에서 시간이 굉장히 오래걸렸다.
list는 유저가 신고한 유저들이 객체형태로 저장되어있다. count는 유저가 신고당한 횟수가 객체형태로 저장되어있다. report 배열을 반복해서 방문하면서, list 객체에 신고한 유저를 추가하고, count 객체에 신고횟수를 더해준다.res에 메일 갯수를 push한다.res를 리턴한다. function solution(id_list, report, k) {
const list = {};
const count = {};
const res = [];
for(let i=0; i<id_list.length; i++) {
list[id_list[i]]={};
count[id_list[i]]=0;
}
for(let i=0; i<report.length; i++) {
const ppl = report[i].split(" ");
const user = ppl[0];
const reportee = ppl[1];
if(!list[user][reportee]) {
list[user][reportee] = 1;
count[reportee]++;
}
}
for(const user in list) {
let mails = 0;
if(list[user]) {
for(const reportee in list[user]) {
if(count[reportee] >= k) {
mails++
}
}
}
res.push(mails);
}
return res;
}
Set을 사용해서 한 유저가 다른 유저를 여러번 신고하는 경우를 제거했고, Map을 사용해서 각 변수의 기능을 분리해서 저장했다. 특히 3번째 테스트케이스가 가장 오래 걸리는데, 여기서 192ms정도가 소요되어 나의 풀이에 비해 63ms정도 빠르다.
[신고한 유저, 신고당한 유저]의 형태로 report에 저장한다. function solution(id_list, report, k) {
let reports = [...new Set(report)].map((el) => {
return el.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((el) => good.get(el) ||0);
return answer;
}