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

SeHoony·2022년 8월 16일
1

코테준비

목록 보기
3/27

1. 문제

신고결과받기(레벨 1)
https://school.programmers.co.kr/learn/courses/30/lessons/92334

2. 풀이

제한사항에 보면 report 배열이 1~200000이다.
이를 보았을 때, O(n2)은 쓸 수 없다는 것을 알 수 있고, O(n) 정도로 가도 가뿐할 것으로 예상된다.

2-1.

function solution(id_list, report, k) {
    const answer = Array.from({length: id_list.length}, () => 0);
    const newReport = [...new Set(report)]
    newReport.map(e => {
        let count = 0
        let [x,y] = e.split(" ")
        newReport.map(e2 => {
           if(y === e2.split(" ")[1]){
               count ++
           } 
        })
        if(count >= k){
            answer[id_list.indexOf(x)] +=1
        }
    })
    return answer;
}

newReport를 두 번 연속 map함수를 써서 배열 전체를 돌기 때문에 O(n2)이 뜬다. 그래서 시간초과로 틀린다.

function solution(id_list, report, k) {
  // 함수 길이와 초기값 지정
    const answer = new Array(id_list.length)
    answer.fill(0)
    
  // 중복 제거
    const newReport = [...new Set(report)]
    const report_id = {}
    
  // 객체를 만들고 그 키값에 원하는 값을 넣어줌
    id_list.map(e => {
        report_id[e] = []
    })
    
    newReport.map(e => {
        const [x,y] = e.split(" ")
        report_id[y].push(x)
    })
    
    id_list.map(e => {
        if(report_id[e].length >= k){
            report_id[e].map(e => {
                answer[id_list.indexOf(e)] +=1
            })
        }
    })
    return answer;
}
profile
두 발로 매일 정진하는 두발자, 강세훈입니다. 저는 '두 발'이라는 이 단어를 참 좋아합니다. 이 말이 주는 건강, 정직 그리고 성실의 느낌이 제가 주는 분위기가 되었으면 좋겠습니다.

0개의 댓글