import java.util.*;
class Solution {
public int[] solution(String[] id_list, String[] report, int k) {
int[] answer = new int[id_list.length];
ArrayList<User> users = new ArrayList<>();
HashMap<String,Integer> suspendedList = new HashMap<>(); //<이름>
HashMap<String,Integer> idIdx = new HashMap<String,Integer>(); // <이름, 해당 이름의 User 클래스 idx>
int idx = 0;
for(String name : id_list) {
idIdx.put(name,idx++);
users.add(new User(name));
}
for(String re : report){
String[] str = re.split(" ");
//suspendedCount.put(str[0], suspendedCount.getOrDefault(str[0],0)+1);
users.get( idIdx.get(str[0])).reportList.add(str[1]);
users.get( idIdx.get(str[1])).reportedList.add(str[0]);
}
for(User user : users){
if(user.reportedList.size() >= k)
suspendedList.put(user.name,1);
}
for(User user : users){
for(String nameReport : user.reportList){
if(suspendedList.get(nameReport) != null){
answer[idIdx.get(user.name)]++;
}
}
}
return answer;
}
}
class User{
String name;
HashSet<String> reportList;
HashSet<String> reportedList;
public User(String name){
this.name = name;
reportList = new HashSet<>();
reportedList = new HashSet<>();
}
}
객체지향을 사용한 코딩
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
class Solution {
public int[] solution(String[] id_list, String[] report, int k) {
List<String> list = Arrays.stream(report).distinct().collect(Collectors.toList());
HashMap<String, Integer> count = new HashMap<>();
for (String s : list) {
String target = s.split(" ")[1];
count.put(target, count.getOrDefault(target, 0) + 1);
}
return Arrays.stream(id_list).map(_user -> {
final String user = _user;
List<String> reportList = list.stream().filter(s -> s.startsWith(user + " ")).collect(Collectors.toList());
return reportList.stream().filter(s -> count.getOrDefault(s.split(" ")[1], 0) >= k).count();
}).mapToInt(Long::intValue).toArray();
}
}
Stream api를 사용한 코딩
import java.util.*;
class Solution {
public int[] solution(String[] id_list, String[] report, int k) {
HashMap<String, HashSet<String>> reportHash = new HashMap<>();
HashMap<String, HashSet<String>> resultHash = new HashMap<>();
for(String r : report){
// 신고유저, 신고당한 유저를 공백을 기준으로 분리
String[] str = r.split(" ");
if(reportHash.containsKey(str[0])==false)
reportHash.put(str[0], new HashSet<>());
// set에서 가져와서 불량유저 추가
reportHash.get(str[0]).add(str[1]);
// 최초인지 확인
if(resultHash.containsKey(str[1])==false)
resultHash.put(str[1], new HashSet<>());
resultHash.get(str[1]).add(str[0]);
}
// id 갯수만큼 생성
int[] answer = new int[id_list.length];
for(int i=0; i<answer.length; i++){
String user = id_list[i];
// 신고한 유저가 없으면 받을 메일이 없으므로 건너뛴다
if(reportHash.containsKey(user)==false) continue;
// bad = 신고한 유저 목록
for(String bad : reportHash.get(user))
if(resultHash.get(bad).size()>=k)
answer[i]++;
}
return answer;
}
}
공부할 때 참고하자!