Post

Programmers 42576 완주하지 못한 선수 (해시)

Programmers 42576 완주하지 못한 선수 (해시)

문제

해시 문제

복잡도 분석

생략

접근법

생략

풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <string>
#include <vector>
#include <unordered_map>

using namespace std;

string solution(vector<string> participant, vector<string> completion) {
    string answer = "";
    unordered_map<string,int> m;
    for(int i=0;i<participant.size();i++){
        if (m.find(participant[i])==m.end()) m.insert({participant[i],1});
        else {
            m[participant[i]]++;
        }
    }
    for(int i=0;i<completion.size();i++){
        auto &e = m[completion[i]];
        e--;
        if (e==0) m.erase(completion[i]);
    }
    for(auto &e:m){
        answer = e.first;
    }
    return answer;
}

개선 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <string>
#include <vector>
#include <unordered_map>

using namespace std;

string solution(vector<string> participant, vector<string> completion) {
    unordered_map<string, int> m;

    // 1. operator[]의 특징 활용: 키가 없으면 0으로 자동 생성 후 ++
    for (const auto& name : participant) {
        m[name]++;
    }

    // 2. 완주자 제거
    for (const auto& name : completion) {
        m[name]--;
        if (m[name] == 0) {
            m.erase(name);
        }
    }

    // 3. 마지막에 남은 단 한 명 반환
    return m.begin()->first;
}

그냥 파이썬처럼 [] operator 쓰기, 없다면 0으로 자동생성됨(원시타입 경우)

마지막 반환은 첫번째거라서 m.begin()->first;

This post is licensed under CC BY 4.0 by the author.