TIL (2022.03.11)
➕ 오늘 푼 문제
프로그래머스 - 신고 결과 받기
➕ 아이디어
report
에서 중복을 제거한다.
- 아이디별 신고 받은 횟수를 담는 해시(
report_count
)를 만든다
- key: 아이디 / value : 신고 받은 횟수
report
를 반복하며, 유저가 신고한 ID가 신고 받은 횟수가 k
번 이상이면 유저ID는 메일을 받는다. 따라서 유저ID의 answer
값을 1 증가시킨다.
- 유저가 신고한 ID가 신고 받은 횟수 = key가 유저가 신고한 ID인
report_count
의 value
➕ Java 코드
import java.util.*;
class Solution {
public int[] solution(String[] id_list, String[] report, int k) {
int[] answer = new int[id_list.length];
HashMap<String, Integer> report_count = new HashMap<String, Integer>();
HashSet<String> report_set = new HashSet<String>(Arrays.asList(report));
for(String r: report_set){
String key = r.split(" ")[1];
report_count.put(key, report_count.getOrDefault(key, 0) + 1);
}
for(String r: report_set){
String[] id = r.split(" ");
if(report_count.get(id[1]) >= k){
int index = Arrays.asList(id_list).indexOf(id[0]);
answer[index] += 1;
}
}
return answer;
}
}
➕ Python 코드
def solution(id_list, report, k):
answer = [0] * len(id_list)
report_count = {i : 0 for i in id_list}
for r in set(report):
from_id, to_id = r.split()
report_count[to_id] += 1
for r in set(report):
from_id, to_id = r.split()
if report_count[to_id] >= k:
index = id_list.index(from_id)
answer[index] += 1
return answer
➕ 궁금한 내용 및 소감
- 해결 아이디어를 내는 것은 어렵지 않았지만, 깔끔하게 구현하는 것이 조금 어려웠던 문제였다. 파이썬, 자바 둘 다 내장 함수를 잘 활용하면 더욱 깔끔하게 풀 수 있었다.
- 파이썬의 경우 dictionary comprehension이나, index() 가 특히 유용했다.
- 자바의 경우 향상된 for문, Arrays.asList(), indexOf() 가 유용했다.
➕ 참고 문헌
- Python - 딕셔너리
- Java - 리스트 중복 제거
- Java - HashSet 반복(향상된 for문)
- Java - 배열에서 특정 값의 인덱스 구하기