코딩테스트/프로그래머스

[프로그래머스] 신고 결과 받기

_Woogie 2022. 12. 29. 00:49

문제 링크

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제 설명

신입사원 무지는 게시판 불량 이용자를 신고하고 처리 결과를 메일로 발송하는 시스템을 개발하려 합니다. 무지가 개발하려는 시스템은 다음과 같습니다.

  • 각 유저는 한 번에 한 명의 유저를 신고할 수 있습니다.
    • 신고 횟수에 제한은 없습니다. 서로 다른 유저를 계속해서 신고할 수 있습니다.
    • 한 유저를 여러 번 신고할 수도 있지만, 동일한 유저에 대한 신고 횟수는 1회로 처리됩니다.
  • k번 이상 신고된 유저는 게시판 이용이 정지되며, 해당 유저를 신고한 모든 유저에게 정지 사실을 메일로 발송합니다.
    • 유저가 신고한 모든 내용을 취합하여 마지막에 한꺼번에 게시판 이용 정지를 시키면서 정지 메일을 발송합니다.

 

 

문제 해설

1. 한 사람이 같은 사람을 계속 신고해도 신고 횟수는 1회이기 때문에 "report"의 중복을 제거한다.
2. "id_list"의 인덱스를 이용해서 신고당한 사람이 k 보다 크거나 같을 때 +1씩 한다.

 

문제 풀이

"report"의 중복을 제거하는 과정에서 filter를 이용했더니 시간초과가 떴다.

Set 객체를 이용해서 풀었다.

function solution(id_list, report, k) {
    const answer = Array(id_list.length).fill(0);
    const cnt = Array(id_list.length).fill(0);
    const blackList = [];
    
    report = [...new Set(report)];
    // 실패 원인
    // report = report.filter((element, index) => report.indexOf(element) === index);
    
    for(let i of report) {
        const [from, to] = i.split(" ");
        const indexTo = id_list.indexOf(to);
        const indexFrom = id_list.indexOf(from);
        cnt[indexTo] += 1;
        
        if(cnt[indexTo] >= k) {
            blackList.push(id_list[indexTo]);
        }
    }
    
    for(let j of report) {
        const [from, to] = j.split(" ");
        if(blackList.includes(to)) {
            const indexFrom = id_list.indexOf(from);
            answer[indexFrom] += 1;
        }
    }
    
    return answer;
}

 

문제 풀이 (다른 사람 코드)

Map을 이용해서 set, get으로 신고당한 사람들을 count해주고, 또 다른 Map에 count get을 해서 신고 당한 횟수가 k이상인 사람을 +1씩 해준다.

이 풀이가 내 풀이보다 훨씬 빨랐다.

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;
}