저번에 이 문제를 해결 할 때, 중첩반복문에 대한 내용도 모르고있었고, 시간복잡도에 대한 내용도 모르고 있었다.
시간복잡도를 해결하고, HashSet을 이용한 중복제거 처리를 먼저 해주니 코드가 훨씬 간결 해 져서 문제 풀이가 완성되었다.
int[] answer = new int[id_list.length];
// answer에 넣어줄 값
HashMap<String, Integer> aCnt = new HashMap<String, Integer>();
// key : 유저, value : 신고 당한 횟수
HashMap<String, Integer> banCnt = new HashMap<String, Integer>();
// 유저 별 신고 당한 횟수 (초기값 0)
for(String i : id_list) {
banCnt.put(i, 0);
aCnt.put(i, 0);
}
// 유저 별 신고 한 유저 담아주기
for(String b : report) {
String[] bu = b.split(" ");
int bc = banCnt.get(bu[1]);
banCnt.put(bu[1], bc + 1);
}
//중복되는지 검사
for(int i = 0; i < report.length; i++) {
int repOvl = -1;
for(int j = 0; j < report.length; j++) {
if(report[i].equals(report[j])) {
++repOvl;
}
}
if(i>0) {
if(i==1) {
if(report[i].equals(report[0])) {
repOvl = 0;
}
} else {
for(int x = 0; x < i; x++) {
if(report[i].equals(report[x])) {
repOvl = 0;
}
}
}
}
String[] bu = report[i].split(" ");
int bc = banCnt.get(bu[1]);
banCnt.put(bu[1], bc - repOvl);
}
//신고당한 회수 k번 이상이면...
for(int i = 0; i < id_list.length; i++) {
if(banCnt.get(id_list[i])>=k) {
for(int j = 0; j < report.length; j++) {
if(report[j].split(" ")[1].equals(id_list[i])) {
int bcnt = aCnt.get(report[j].split(" ")[0]);
if(j>0) {
if(j==1) {
if(report[j].equals(report[0])) {
} else {
aCnt.put(report[j].split(" ")[0], bcnt + 1);
}
} else {
for(int x = 0; x < j; x++) {
if(report[j].equals(report[x])) {
} else {
aCnt.put(report[j].split(" ")[0], bcnt + 1);
}
}
}
} else {
aCnt.put(report[j].split(" ")[0], bcnt + 1);
}
}
}
}
}
for(int i = 0; i < id_list.length; i++) {
answer[i] = aCnt.get(id_list[i]);
}
라는 내용의 말도안되는 코드였는데, 이 다음날 강사님에게 코딩테스트 시간초과가 왜나오는지 여쭤봤고, 일반적으로 중첩반복문 때문인 경우가 많다고 하셔서 그쪽에 집중했고, 코드도 전체적으로 삭제한 다음 다시 생각 해 보기 시작했다
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
class Solution {
public int[] solution(String[] id_list, String[] report, int k) {
int[] answer = new int[id_list.length];
//user 별 신고 당한 횟수
HashMap<String,Integer> banCnt = new HashMap<String,Integer>();
//answer에 넣어 줄 값
HashMap<String,Integer> aCnt = new HashMap<String,Integer>();
//user 별 신고 당한 횟수, answer에 넣어 줄 값 Mapping 처리 (초기값 0)
for(String il : id_list) {
banCnt.put(il, 0);
aCnt.put(il, 0);
}
//report 에서 중복 제거 작업을 먼저 해준다면?
HashSet hashSet = new HashSet();
for(String rp : report) {hashSet.add(rp);}
ArrayList<String> dor = new ArrayList<>(hashSet);
for(String d : dor) {
String bun = d.split(" ")[1];
int cnt = banCnt.get(bun);
banCnt.put(bun, cnt + 1);
}
for(String d : dor) {
if(banCnt.get(d.split(" ")[1]) >= k) {
aCnt.replace(d.split(" ")[0], aCnt.get(d.split(" ")[0])+1);
}
}
for(int i = 0; i < id_list.length; i++) {
answer[i] = aCnt.get(id_list[i]);
}
return answer;
}
}
이때 정말 약간 크게 배운 것 같았다.
열심히 공부해야지.