CS
[์๋ฃ๊ตฌ์กฐ] ํด์ ํ ์ด๋ธ (Hash Table)
moaoh
2024. 11. 8. 02:11
ํด์ ํ ์ด๋ธ (Hash Table) ๋?
- ํค-๊ฐ ์์ ๋น ๋ฅด๊ฒ ์ฝ์ , ์กฐํ, ์ ๊ฑฐํ๋ ๋ฐ ์ฌ์ฉ๋๋ ๋ฐ์ดํฐ ๊ตฌ์กฐ
์ฅ๋จ์
์ฅ์
- ํ๊ท ์ ์ผ๋ก O(1)์ ์๊ฐ์ ๊ฒ์, ์ฝ์ , ์ญ์ ๊ฐ ๊ฐ๋ฅํด ๋น ๋ฆ.
- ํฐ ๋ฐ์ดํฐ๋ฅผ ๊ด๋ฆฌํ๊ธฐ์ ์ ๋ฆฌํ๋ฉฐ, ์ค๋ณต ๋ฐ์ดํฐ ๋ฐฉ์ง์ ์ ์ฉ.
๋จ์
- ์ถฉ๋ ๋ฐ์ ์ ์ฑ๋ฅ์ด ์ ํ๋ ์ ์์.
- ํด์ ํจ์์ ๋ฐ๋ผ ์ฑ๋ฅ์ด ๋ฌ๋ผ์ง ์ ์์ผ๋ฉฐ, ๋ฉ๋ชจ๋ฆฌ ํจ์จ์ฑ์ด ๋จ์ด์ง ์ ์์.
๊ตฌํ
vector๋ฅผ ์ฌ์ฉํ ๊ตฌํ
#include <iostream>
#include <vector>
#include <algorithm>
class HashTable
{
private:
int BUCKET;
std::vector<std::vector<int> > table;
public:
HashTable(int b) {
this->BUCKET = b;
table.resize(BUCKET);
}
~HashTable() {};
// ์ ์ผํ ์ธ๋ฑ์ค๋ก ๋งคํํ๋ ์ญํ
int hashFunction(int x) {
return (x % BUCKET);
}
void insertItem(int key) {
int index = hashFunction(key);
table[index].push_back(key); // Chaining ๋ฐฉ์
}
void deleteItem(int key) {
int index = hashFunction(key);
auto it = std::find(table[index].begin(), table[index].end(), key);
if (it != table[index].end()) {
table[index].erase(it);
}
}
void displayHashTable() {
for (int i = 0; i < BUCKET; i++) {
std::cout << i;
for (int it : table[i]) {
std::cout << " --> " << it;
}
std::cout << std::endl;
}
}
};
int main() {
std::vector<int> a = {15, 11, 27, 8, 12};
HashTable h(7);
for (int key : a)
h.insertItem(key); // hashTable์ ๊ฐ ์ ์ฅ
// hashTable์์ 12 ์ญ์
h.deleteItem(12);
// ์ ์ฒด ์ถ๋ ฅ
h.displayHashTable();
return 0;
}
output
0
1 --> 15 --> 8
2
3
4 --> 11
5
6 --> 27
- key๋ฅผ ๋ฐํ์ผ๋ก value๋ฅผ ์ฐพ์ ์ ์๊ธฐ๋๋ฌธ์ ๋ณด๋ค ๋น ๋ฅด๊ฒ O(1) ~ O(n) ์ ๋๋ก value๋ฅผ ์ฐพ๋๊ฒ์ด ๊ฐ๋ฅํ๋ค.