Bảng băm (Hash Table)
Hash Table là gì?
Hash Table là cấu trúc dữ liệu lưu trữ cặp key-value, cho phép truy cập dữ liệu rất nhanh - trung bình O(1).
💡
Hash Table giống như quyển từ điển - bạn tra từ (key) và tìm nghĩa (value) rất nhanh!
Sử dụng Hash Table
Python
# Python dùng dict
person = {"name": "John", "age": 30}
# Truy cập
print(person["name"]) # "John"
print(person.get("email")) # None
# Thêm/Sửa
person["email"] = "[email protected]"
# Xóa
del person["email"]
# Kiểm tra tồn tại
if "name" in person:
print("Có key 'name'")Độ phức tạp
| Thao tác | Trung bình | Xấu nhất |
|---|---|---|
| Insert | O(1) | O(n) |
| Search | O(1) | O(n) |
| Delete | O(1) | O(n) |
Two Sum Problem
Python
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []Đếm tần suất
Python
from collections import Counter
def frequency_count(arr):
return dict(Counter(arr))
# Hoặc tự implement
def frequency_count(arr):
freq = {}
for num in arr:
freq[num] = freq.get(num, 0) + 1
return freqỨng dụng thực tế
| Ứng dụng | Mô tả |
|---|---|
| Database indexing | Tìm kiếm nhanh trong DB |
| Caching | LRU Cache, Memcached |
| Counting | Đếm tần suất phần tử |
| Set | Kiểm tra phần tử tồn tại |
Tiếp theo: Cây (Tree)
Last updated on