[Programmers] Level1 : 신고 결과 받기
Question
Solution
- 중복 신고 방지를 위해 set과 map을 활용한다. map<신고한 사람, set<신고 받은="" 사람="">> reportMap; map<신고 받은 사람, set<신고 한="" 사람="">> resultMap;신고>신고>
- 공백을 두고 신고자와 신고 받은 사람을 구분시켜 map을 채운다. (report.size()만큼 for문을 돌린다)
-
id_list만큼 for문을 돌고 신고 내역이 있다면 신고 받은 유저의 크기가 k 보다 크면 1씩 더해준다.
- 추가: 공백을 find(‘ ‘)로 찾고, substr()로 더 깔끔한 코드로 바꿀 수 있다.
Cord
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
vector<int> solution(vector<string> id_list, vector<string> report, int k)
{
vector<int> answer(id_list.size());
unordered_map<string, unordered_set<string>> reportMap;
unordered_map<string, unordered_set<string>> resultMap;
// 신고 건수 만큼 반복
for(int i = 0; i < report.size(); i++)
{
// 공백 찾기
int splitIdx;
for (int j = 0; j < report[i].size(); j++)
{
if (report[i][j] == ' ')
{
splitIdx = j;
}
}
// 신고자와 대상 분리
string reporter = "";
string reported = "";
for(int j = 0; j < splitIdx; j++) { reporter += report[i][j]; }
for(int j = splitIdx + 1; j < report[i].size(); j++) { reported += report[i][j]; }
// 신고 map 채우기
reportMap[reporter].insert(reported);
resultMap[reported].insert(reporter);
}
// 신고 결과 카운트
for(int i = 0; i < id_list.size(); i++)
{
auto it = reportMap.find(id_list[i]);
if (it == reportMap.end()) { continue; }
for(string target : it->second)
{
if (resultMap[target].size() >= k)
{
answer[i]++;
}
}
}
return answer;
}