๐Ÿ“ Coding Test Study/C++

[C++] Hash ์ž๋ฃŒ๊ตฌ์กฐ / unordered_map ์‚ฌ์šฉ๋ฒ•(feat. map)

ibelieveinme 2021. 10. 31. 23:38
728x90

C++์€ ํ•ด์‹œํ…Œ์ด๋ธ”์„ unordered_map ์ด๋ผ๋Š” STL๋กœ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

unordered_map ํด๋ž˜์Šค

๋‹ค์–‘ํ•œ ๊ธธ์ด์˜ ์š”์†Œ ์‹œํ€€์Šค๋ฅผ ์ œ์–ดํ•˜๋Š” C++ ํ‘œ์ค€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์ปจํ…Œ์ด๋„ˆ ํด๋ž˜์Šค ์— ๋Œ€ํ•œ API `unordered_map` ์ฐธ์กฐ์ž…๋‹ˆ๋‹ค.

docs.microsoft.com

 

* ์‹œ๊ฐ„๋ณต์žก๋„

ํ•ด์‰ฌํ…Œ์ด๋ธ”์€ key ๊ฐ’์œผ๋กœ ํƒ์ƒ‰ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํƒ์ƒ‰ ์‹œ๊ฐ„๋ณต์žก๋„๋Š” O(1) ๋ฐ–์— ๊ฑธ๋ฆฌ์ง€ ์•Š๋Š”๋‹ค. ๋˜ํ•œ, ์ •๋ ฌํ•  ํ•„์š”๊ฐ€ ์—†์œผ๋ฏ€๋กœ ๋ฐ์ดํ„ฐ ์ถ”๊ฐ€, ์‚ญ์ œ ์‹œ์—๋„ ๊ทธ ์„ฑ๋Šฅ์ด ๊พธ์ค€ํžˆ ๋ณด์žฅ๋œ๋‹ค.

 

* map vs unordered_map

map ์€ ์ •๋ ฌ์ด ๋œ๋‹ค. ๋ ˆ๋“œ๋ธ”๋ž™ํŠธ๋ฆฌ๊ธฐ๋ฐ˜์ด๋ฏ€๋กœ ํƒ์ƒ‰, ์‚ฝ์ž…, ์‚ญ์ œ์— O(longN)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ๊ฑธ๋ฆฐ๋‹ค.

unordered_map ์€ ์ •๋ ฌ์ด ์•ˆ๋œ๋‹ค. ํ•ด์‹œํ…Œ์ด๋ธ” ๊ธฐ๋ฐ˜์ด๋ฏ€๋กœ ํƒ์ƒ‰, ์‚ฝ์ž…, ์‚ญ์ œ์— ํ‰๊ท  O(1), ์ตœ์•…์˜ ๊ฒฝ์šฐ O(N) ์ด ๊ฑธ๋ฆฐ๋‹ค.

 

* ์‚ฌ์šฉ๋ฐฉ๋ฒ•

#include <iostream>
#include <unordered_map>//include
using namespace std;

int main(){
    unordered_map<string, int> map; //์„ ์–ธ

    //๋ฐ์ดํ„ฐ ์‚ฝ์ž…
    map.insert(make_pair("a", 1));
    map.insert(make_pair("b", 2));
    map.insert(make_pair("c", 3));

    //๋ฐ์ดํ„ฐ ํƒ์ƒ‰
    map.find("a");
    cout << "map["a"].first: " << map["a"].first; // a
    cout << "map["a"].second: " << map["a"].second; // 1
    map.count("a");//key๊ฐ€ "a"์ธ ์›์†Œ์˜ ๊ฐœ์ˆ˜ ๊ตฌํ•˜๊ธฐ
    
    //๋ฐ์ดํ„ฐ ์ˆœํšŒ
    for(auto& i: map){
    	if(i.first == "b") i.second ++; // map["b"].second = 2;
    }
    
    //๋ฐ์ดํ„ฐ ์ˆ˜์ •
    map["a"] = 2;
    cout << "map["a"].second: " << map["a"].second; // 2

    //๋ฐ์ดํ„ฐ ์‚ญ์ œ
    map.erase("a");
    
    //๊ธฐํƒ€
    map.empty(); // ๋น„์–ด์žˆ์œผ๋ฉด true, ๊ทธ๋ ‡์ง€ ์•Š๋‹ค๋ฉด false๋ฅผ ๋ฐ˜ํ™˜
    map.size(); // map์˜ ํฌ๊ธฐ๋ฅผ ๋ฐ˜ํ™˜

    return 0;
}

 

*๊ด€๋ จ๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์™„์ฃผํ•˜์ง€ ๋ชปํ•œ ์„ ์ˆ˜

์ˆ˜๋งŽ์€ ๋งˆ๋ผํ†ค ์„ ์ˆ˜๋“ค์ด ๋งˆ๋ผํ†ค์— ์ฐธ์—ฌํ•˜์˜€์Šต๋‹ˆ๋‹ค. ๋‹จ ํ•œ ๋ช…์˜ ์„ ์ˆ˜๋ฅผ ์ œ์™ธํ•˜๊ณ ๋Š” ๋ชจ๋“  ์„ ์ˆ˜๊ฐ€ ๋งˆ๋ผํ†ค์„ ์™„์ฃผํ•˜์˜€์Šต๋‹ˆ๋‹ค. ๋งˆ๋ผํ†ค์— ์ฐธ์—ฌํ•œ ์„ ์ˆ˜๋“ค์˜ ์ด๋ฆ„์ด ๋‹ด๊ธด ๋ฐฐ์—ด participant์™€ ์™„์ฃผํ•œ ์„ ์ˆ˜

programmers.co.kr

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

string solution(vector<string> participant, vector<string> completion) {
    string answer = "";
    unordered_map<string, int> map;
    
    for(auto& person : participant) map[person]++;
    for(auto& person : completion) map[person]--;
    for(auto& person : map) {
        if(person.second != 0) {
            answer = person.first;
            break;
        }
    }
    
    return answer;
}

 

728x90