본문 바로가기
알고리즘

[프로그래머스] Lv 1. 신고 결과 받기 - Javascript 풀이

by daami 2025. 1. 11.

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/92334

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

풀이

<첫 답안> 

function solution(id_list, report, k) {
    const idCount = id_list.length;
    const result = Array(idCount).fill(0); //각 유저별 신고 당한 횟수
    const alreadyReport = []; //중복이 제거된 신고 배열
    const record = Array.from({length: idCount}, ()=>[]); //신고기록
    let answer = Array(idCount).fill(0); //각 유저별로 처리 결과 메일을 받은 횟수 
    
    report.forEach((item)=>{
        const [user, reportedUser] = item.split(' ');
        
        //같은 유저가 신고하지 않은 경우
        if(!alreadyReport.includes(item)){
            alreadyReport.push(item);
            //신고 당한 횟수 업데이트
            const reportedUserIndex = id_list.indexOf(reportedUser);
            result[reportedUserIndex]++;
            //신고 기록 업데이트
            const userIndex = id_list.indexOf(user);
            record[userIndex].push(reportedUser);
        }
    });
    
    result.forEach((time, index)=>{
        if(time>=k){
            record.forEach((row, i)=>{
               if(row.includes(id_list[index]))
                   answer[i]++;
            })
        }
    });
    
    return answer; 
}

 

이렇게 했더니 테스트케이스는 통과했으나, 제출하였을 때 다른 테스트케이스 2개에서 시간초과로 실패했다.

비효율적인 부분이 무엇인가, 고민하다가 먼저 중복된 신고를 확인하는 부분을 수정했다. 굳이 배열을 만들고 includes를 통해 확인하지 않아도 자바스크립트의 Set 객체를 이용하면 되었다.

 

<수정한 답안>

function solution(id_list, report, k) {
    const idCount = id_list.length;
    const result = Array(idCount).fill(0); //각 유저별 신고 당한 횟수
    const uniqueReport = [...new Set(report)]; //중복이 제거된 신고 리스트
    const record = Array.from({length: idCount}, ()=>[]); //신고기록
    let answer = Array(idCount).fill(0); //각 유저별로 처리 결과 메일을 받은 횟수 
    
    uniqueReport.forEach((item)=>{
        const [user, reportedUser] = item.split(' ');
        
            //신고 당한 횟수 업데이트
            const reportedUserIndex = id_list.indexOf(reportedUser);
            result[reportedUserIndex]++;
            //신고 기록 업데이트
            const userIndex = id_list.indexOf(user);
            record[userIndex].push(reportedUser);
    });
    
    result.forEach((time, index)=>{
        if(time>=k){
            record.forEach((row, i)=>{
               if(row.includes(id_list[index]))
                   answer[i]++;
            })
        }
    });
    
    return answer; 
}