πŸ“ 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