오늘의 인기 글
최근 글
최근 댓글
Today
Total
05-09 00:00
관리 메뉴

우노

[프로그래머스] “신고 결과 받기” C++ 풀이 본문

Algorithm/Kakao

[프로그래머스] “신고 결과 받기” C++ 풀이

운호(Noah) 2022. 4. 26. 23:17

문제 링크

문제 풀이

  • 주요 풀이
    • 각 멤버의 index를 Map에 저장
    • 신고된ID와 신고한ID를 Map에 저장
      • 이때, 신고한ID는 중복을 제거하기 위해, Set 형태로 저장
    • 신고 정보 문자열은 stringstream을 사용해 parsing
  • 전체 흐름
    • 신고 정보들을 parsing한 뒤, 신고 정보를 저장하는 Map에 전부 담고,
    • 신고 정보 Map을 탐색하면서, 신고한ID의 개수가 K개 이상이면,
    • 신고한 멤버들의 Count를 증가시키는 방식

예제 코드

#include <string>
#include <vector>
#include <map>
#include <set>
#include <sstream>

using namespace std;

vector<int> solution(vector<string> id_list, vector<string> report, int k) {

    // 결과 Vector를 0으로 초기화
    vector<int> answer(id_list.size(), 0);

    // 각 멤버의 index를 Map에 저장
    map<string, int> id_idx_map;

    // [신고된ID, 신고한ID]를 저장할 Map 생성
    map<string, set<string>> report_map;

    // 각 멤버의 index를 Map에 저장
    for (auto i=0; i<id_list.size(); ++i){
        id_idx_map[id_list[i]] = i;
    }

    // [신고된ID, 신고한ID]를 Map에 저장
    for (auto rep : report){

        // 문자열 형태의 각 신고 정보를 parsing
        stringstream ss(rep);
        string from, to;
        ss >> from >> to;

        // [신고된ID, 신고한ID] 형태로 Map에 저장
        // report_map의 Value는 Set 형태이므로, 바로 insert 가능
        report_map[to].insert(from);

    }

    // report_map을 탐색하며, 신고한ID의 개수가 K개 이상일 경우, 신고한ID들의 메일수를 +1
    for (auto iter : report_map){
        if (iter.second.size() >= k){
            for (auto in_iter : iter.second){
                answer[id_idx_map[in_iter]]++;
            }
        }
    }

    return answer;
}

참고

'Algorithm > Kakao' 카테고리의 다른 글

[프로그래머스] “신규 아이디 추천” C++ 풀이  (0) 2022.05.06
Comments