Skip to Content
🧮 CTDL & Giải thuật🗂️ Bảng băm (Hash Table)

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 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ácTrung bìnhXấu nhất
InsertO(1)O(n)
SearchO(1)O(n)
DeleteO(1)O(n)

Two Sum Problem

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

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ụngMô tả
Database indexingTìm kiếm nhanh trong DB
CachingLRU Cache, Memcached
CountingĐếm tần suất phần tử
SetKiểm tra phần tử tồn tại

Tiếp theo: Cây (Tree)

Last updated on