* hash table
๐ค ๋ฐ๋์ ์์์ผ ํ ์๋ฃ๊ตฌ์กฐ - ํด์(Hash)์ ๋ํด์ ์์๋ณด์!
๐ค ํ์ด์ฌ์์ ํด์ ํ ์ด๋ธ์ dictionary๋ผ๋ ์๋ฃ๊ตฌ์กฐ๋ฅผ ํตํด ๊ตฌํํ ์ ์๋ค. dict() ํด๋์ค์ ๊ตฌํ๋์ด ์์.
โ list์ ๊ฒฝ์ฐ ์ซ์๋ก๋ง indexing - ์ฆ ์๋ฃ ์ ๊ทผ์ด ๊ฐ๋ฅํ์ง๋ง, dictionary์ ๊ฒฝ์ฐ key๋ผ๋ ํน์ํ index๋ฅผ ํตํด ์ ๊ทผ ๊ฐ๋ฅ
โก dictionary ํจ์ time complexity๋ ๋๋ถ๋ถ O(1) ๋งค์ฐ ๋น ๋ฆ
โ list vs. dictionary time complexity โ
operation | dictionary | list |
get item | O(1) | O(1) |
insert item | O(1) | O(1) ~ O(N) |
update item | O(1) | O(1) |
delete item | O(1) | O(1) ~ O(N) |
search item | O(1) | O(N) |
๐ค set() / dict() <์งํฉ๊ณผ ๋งต> ๋ด์ฉ ์ฐธ์กฐ ํฌ์คํ
* hash function & hashing
๐ค hash function์ด๋?
→ ์์ ๊ธธ์ด ๋ฐ์ดํฐ(input)๋ฅผ "์ํธํ๋ ๊ณ ์ ๊ธธ์ด(output)"์ ๋ฐ์ดํฐ๋ก ๋งคํ(์ ํ)ํ๋ ํจ์
→ ์ถ๋ ฅ๋๋ ๋ฐ์ดํฐ๋ ๋ชจ๋ ๋์ผ๊ธธ์ด. ํ์ง๋ง input๋๋ ๊ฐ๋ค์ ๋จ ํ ๊ธ์๋ง ์ฐจ์ด๊ฐ ์์ด๋ ์์ ํ ๋ค๋ฅธ ๊ฒฐ๊ณผ๊ฐ ์ถ๋ ฅ
๐ค hash function๊ณผ hash table๊ณผ์ ์ฐ๊ด์ฑ
→ ๋ค์ํ key๊ฐ(hash func์์์ input๋ค)์ hash func์ ๋ฃ๊ณ ๋ ๋ค์์ ์ฌ๋ฌ output๋ค์ธ hash๋ค์ด hash table์ index๋ก ์ฐ์ด๊ณ , ์ฐ๋ฆฌ๊ฐ ์ ๋ง๋ก ์ํ๋ ํด๋น key์ ๋์ํ๋ value๋ hash table์ index์ ๋์ํ๋ value๋ก ๊ตฌ์ฑ๋๋ค.
→ ํ์ด์ฌ์์์ hash table์ dictionary๋ฅผ ๋ปํจ.
๐ค ๊ทธ๋ ๋ค๋ฉด hashing์?
→ ์ ๊ฐ๋ ์ ๋ฆฌํ hash table์์ indexing, ์ฆ ๋ด๊ฐ ์ํ๋ value๋ฅผ ์ฐพ๊ธฐ ์ํด key๋ฅผ hash function์ ๋ฃ๋ ๊ณผ์ - ์ฆ hash function์ ์ฌ์ฉํ๋ ๊ณผ์ ์ hashing์ด๋ผ๊ณ ํ๋ค.
๐ค ์ ๋ฆฌํ์๋ฉด, key๋ฅผ hash function์ ๋ฃ๋ hashing output์ธ hash๊ฐ index๊ฐ ๋๊ณ , ์ด index์ ๋ง๋, ์ฆ key์ ๋์ํ๋ value ํ ์ (key, value)๊ฐ hash table์ ์ ์ฅ๋๋ค.
key → hash(index) → (key. value) ์ ์ฅ
* hash table ex)
๐ค ์ ์์ ์ค๋ช
→ stock_prices๋ผ๋ dictionary - ์ฆ hash table์ด ์๋ค
→ 'march 6'๋ผ๋ key๋ฅผ hash function์ ํตํ hashing ๊ฒฐ๊ณผ index 9๊ฐ ๋์๊ณ , index 9์ ๋์ํ๋, ์ฆ 'march 6'์ ๋์ํ๋ value 310์ด ์ ์ฅ
* hash collision>
๐ค hash์์ ์ค์ํ ๊ฑด, ์๋ก ๋ค๋ฅธ input์ key๊ฐ hash func๋ฅผ ๊ฑฐ์น ํ ๋์ผํ output(same hashes)์ผ๋ก ๋์จ ๊ฒฝ์ฐ, ์ด๋ฅผ ์ฐ๋ฆฌ๋ 'ํด์ ์ถฉ๋(hash collision)'์ด๋ผ๊ณ ํ๋ค.
๐ค ์ข์ hash function
→ ์ข์ ํด์ฌ ํจ์๋, ๊ฐ๋ณ์ ์ผ๋ก ์๋ก ๋ค๋ฅธ input๋ค์ด hash function์ ๊ฑฐ์น ๊ฒฐ๊ณผ ์ต๋ํ ๊ฐ๊ฐ ๋ค๋ฅธ hash๋ก ๋์ค๊ฒ ํด์ฃผ๋, ์ฆ ์ถฉ๋์ ์ต์ํํ๋ ํจ์๋ฅผ ๋งํ๋ค.
๐ค solutions
โ seperate chaining
→ ์ถฉ๋ ๋ฐ์ ์ ๋์ผํ key์ ๋ค๋ฅธ value๋ค์ ์ผ์ข ์ ์ฐ๊ฒฐ๋ฆฌ์คํธ๋ก ์ฐ๊ฒฐํด ์ถฉ๋์ ํด๊ฒฐ
โก open addressing
→ ์ถฉ๋ ๋ฐ์ ์ ์ ๋น ๊ณต๊ฐ์ ์ฐพ์ ๋๊ฐ ๋น ๊ณต๊ฐ์ ๋ค์ด๊ฐ๊ฒ ํด ์ถฉ๋์ ํด๊ฒฐ
โป handling hash collision ๋ณ๋ ํฌ์คํ ์์
* exercises>
→ ๋ฐฑ์ค hashing ๋ฌธ์ ๋ชจ์
→ ๋ฐฑ์ค hash๋ฅผ ์ฌ์ฉํ ์งํฉ๊ณผ ๋งต ๋ฌธ์ ๋ชจ์
* source1) https://s1m0hya.tistory.com/27
* source2) https://woonys.tistory.com
* source3) https://realpython.com/python-hash-table/
'Computer Science > Data Structures' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ณ Binary Tree ๐ณ (1) | 2023.12.19 |
---|---|
๐ Map (0) | 2023.08.03 |
Types of Binary Tree๐ฒ (0) | 2023.01.10 |
๐ฏPriority Queue(feat. Binary Heap) (0) | 2023.01.09 |
๐stack & queue & deque (0) | 2022.09.23 |
๋๊ธ