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๋ฅผ ์ฐพ๋Š”๊ฒƒ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

์ฐธ๊ณ ์ž๋ฃŒ

https://www.geeksforgeeks.org/hash-table-data-structure/