[알고리즘]-신고 결과 받기

dev_woo·2025년 1월 6일
post-thumbnail

요약

풀이 시간 : 2314초

풀이
1. 중복 제거 
2. 데이터 매핑

다름 사람 풀이를 참고한 리펙토링
1. 중복의 대상을 명확히 하기, -> report에서 target 만 중복처리해서 추가 로직생김
2. || 연산자 활용, -> map.set(id , (map.get(id) || 0) + 1);

문제 링크

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

풀이

function solution(id_list, report, k) {
	// 동일한 유저에 대한 신고는 1번만 Map -> 중복처리
	// k번 이상 신고시 정지 -> 대상자 기준
	// id_list 순서대로 처리

	const reportMailCounts = new Map(id_list.map((id) => [id, 0])); // 유저별 처리 결과 메일
	const reportMap = new Map(id_list.map((id) => [id, new Set()])); // 작성자-메일 매핑, 중복처리를 위해 Set() 사용
	const stopMap = new Map();// ID-누적횟수 매핑

	for (const rep of report) { // 작성자-메일 매핑
		const [id, target] = rep.split(' ');
		reportMap.get(id).add(target);
	}

	for (const targets of reportMap.values()) { // ID-누적횟수 매핑
		for (const id of [...targets]) {
			if (stopMap.has(id)) {
				stopMap.set(id, stopMap.get(id) + 1);
			} else {
				stopMap.set(id, 1);
			}
		}
	}
    
	for (const [id, targets] of reportMap) { // 최종 결과 매핑
		for (const target of [...targets]) {
			if (stopMap.get(target) >= k) {
				reportMailCounts.set(id, reportMailCounts.get(id) + 1);
			}
		}
	}

	return [...reportMailCounts.values()];
}

다른 사람 풀이

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

코드 리펙토링

function solution(id_list, report, k) {
	// 중복 신고 제거
	const uniqueReports = [...new Set(report)].map((rep) => rep.split(' '));

	// 신고당한 횟수 계산
	const reportCounts = new Map();
	for (const [_, target] of uniqueReports){
		reportCounts.set(target, (reportCounts.get(target) || 0) + 1);
	}

	// 신고자별 처리 결과 메일 카운트
	const resultMailCounts = new Map(id_list.map((id) => [id, 0]));
	for (const [reporter, target] of uniqueReports) {
		if (reportCounts.get(target) >= k) {
			resultMailCounts.set(reporter, resultMailCounts.get(reporter) + 1);
		}
	};

	// id_list 순서에 맞는 결과 반환
	return id_list.map((id) => resultMailCounts.get(id));
}
profile
꾸준히 한걸음씩

0개의 댓글