Java/Coding Test

신고 결과 받기 문제풀이

최고다최코딩 2023. 9. 23. 01:55
728x90

유저 아이디 배열과 "신고자 피신고자" 배열, 제재 대상 기준 횟수가 주어질때 ,

신고자가 신고한 유저가 제재 대상이 되면 신고자에게 메일을 보내고

이때 신고자가 받은 메일의 개수를 담은 배열을 반환  

public int[] solution(String[] id_list, String[] report, int k) {

int[] answer = new int[id_list.length];

Map<String,Set<String>> reportedMap = new HashMap<String,Set<String>>();//K:신고당한사람 V:신고한사람SET

ArrayList<String> id = new ArrayList<String>();//answer에 저장할때 index를 알아내기 위해 id_list와 같은 순서로 add

for (int i = 0; i < id_list.length; i++) {

id.add(id_list[i]);

}

for(int i=0; i<report.length;i++){

Set<String> thoseReporting = reportedMap.getOrDefault(report[i].split(" ")[1],new HashSet<String>());//신고한사람SET

thoseReporting.add(report[i].split(" ")[0]);

reportedMap.put(report[i].split(" ")[1],thoseReporting);

}

Set<String> reportedSet = reportedMap.keySet();

for (Iterator iterator = reportedSet.iterator(); iterator.hasNext();) {

String string = (String) iterator.next();

Set<String> a = reportedMap.get(string);

if(a.size()>=k) {

for (Iterator iterator2 = a.iterator(); iterator2.hasNext();) {

String string2 = (String) iterator2.next();

answer[id.indexOf(string2)]++;

}

}

}

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<>();

}

}

유저 객체는

본인 이름과 

본인이 신고한 사람 set, 본인을 신고한 사람 set을 가지고 있다.   

public int[] solution2(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(" ");

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)//신고당한 횟수가 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)]++;//그 이름으로 index 찾아서 answer증가

}

 

}

}

return answer;

 

}