본문 바로가기

코딩 테스트/프로그래머스

[프로그래머스 Level 1, C++] 신고 결과 받기

728x90
반응형

문제 : 신고 결과 받기


풀이 방법

https://youtu.be/SHX3FgLx014

 

처음에는 내 방식 대로 풀었을 때 테스트 케이스는 통과 했었다..

근데 제출하니까 실패 거의 반 이상을 차지해서 좀 더 고민하다가 3시간 이상 넘어가니까 못풀겠더라

그래서 유튜브에 찾아보니까 이렇게 풀이랑 코드랑 같이 있는 것을 보고 배웠다.

 

이분은 map이랑 set을 사용하는데 중복을 없애기 위해 set을 사용한다고 했다.

report.erase(unique(report.begin(), report.end()), report.end());

나는 이거면 중복을 제거 하기 때문에 이거만 쓰고 set을 쓰지 않았는데 오류가 나더라

아마도 set을 써야 하는게 맞았던 것 같다.

 

해쉬랑 set좀 더 공부해야할 것 같다


소스 코드

#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
using namespace std;

vector<int> solution(vector<string> id_list, vector<string> report, int k) {
    vector<int> answer(id_list.size(), 0);
    
    unordered_map<string, unordered_set<string>> report_hash;
    unordered_map<string, unordered_set<string>> result_hash;
    
    for(string & s : report) {
        int pos = s.find(' ');
        string user = s.substr(0, pos);
        string rt = s.substr(pos + 1);
        report_hash[user].insert(rt);
        result_hash[rt].insert(user);
    }
    
    for(int i=0; i<id_list.size(); i++) {
        auto it = report_hash.find(id_list[i]);
        if(it == report_hash.end()) continue;
        for(string rt : it->second) {
            if(result_hash[rt].size() >= k) {
                answer[i]++;
            }
        }
    }
    
    return answer;
}

 

728x90
반응형