문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/92334
[이 문제는 프로그래머스에서 푼 문제입니다.]
이 문제는 HashMap을 이용하여 풀 수 있습니다. 신고를 한 사람과 신고를 당한 사람의 인덱스를 HashMap에서 <사람 이름, 인덱스>로 저장하여 배열에서 사람 이름을 찾으면 해당 인덱스를 가져오는 방식으로 문제의 조건을 처리하면 됩니다.
다음은 코드입니다.
import java.util.*;
class Solution {
public int[] solution(String[] id_list, String[] report, int k) {
// HashMap에 id의 인덱스 저장
HashMap<String,Integer> ids = new HashMap<>();
for(int i=0;i<id_list.length;i++){
ids.put(id_list[i],i);
}
// 유저의 신고 여부 체크
boolean[][] check = new boolean[id_list.length][id_list.length];
// 신고 내역 정리
int[] report_list = new int[id_list.length];
int[] reported_list = new int[id_list.length];
int[] answer = new int[id_list.length];
for(int i=0;i<report.length;i++){
StringTokenizer st = new StringTokenizer(report[i]);
String sendID = st.nextToken();
String receiveID = st.nextToken();
int sendIdx = ids.get(sendID);
int receiveIdx = ids.get(receiveID);
// 한 유저가 신고한 신고 횟수는 1회
if(!check[receiveIdx][sendIdx]){
check[receiveIdx][sendIdx] = true;
reported_list[receiveIdx]++;
}
}
// 신고당한 횟수가 k보다 작을 경우 0으로 치환
for(int i=0;i<reported_list.length;i++){
if(reported_list[i] <k) reported_list[i] = 0;
else{
// 체크 배열 조사해서 신고 기록이 있으면 해당 인덱스 ++
for(int j=0;j<check.length;j++){
if(check[i][j]) answer[j]++;
}
}
}
return answer;
}
}