跳到文档正文
数据结构 / 哈希表
07 / 18
我们的可视化工具通过直观的图形界面支持哈希表操作。在使用哈希表时(Python中的字典或JavaScript中的对象/Map),每个键值对都以可视化方式表示,使得一眼就能理解数据结构的内容。
该工具动态跟踪插入、删除和查找等操作,在代码执行时突出显示受影响的键值对。这种视觉反馈对于学习哈希表概念或调试基于哈希表的算法特别有用。
让我们看看一些常见的哈希表算法及其可视化:
def count_characters(s):
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1
return char_count
# 使用示例
count_characters("hello world")
def word_frequency(sentence):
words = sentence.lower().split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return freq
word_frequency("the quick brown fox jumps over the lazy dog")
def two_sum(nums, target):
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
return []
# 使用示例
two_sum([2, 7, 11, 15], 9)
def find_all_pairs(nums, target):
num_map = {}
pairs = []
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
for prev_index in num_map[complement]:
pairs.append([prev_index, i])
num_map.setdefault(num, []).append(i)
return pairs
find_all_pairs([1, 5, 3, 7, 2, 4, 3], 6)
def fibonacci(n, cache=None):
if cache is None:
cache = {}
# 基本情况
if n < 2:
return n
# 检查结果是否在缓存中
if n in cache:
return cache[n]
# 计算并存储结果
cache[n] = fibonacci(n-1, cache) + fibonacci(n-2, cache)
return cache[n]
# 使用示例
result = fibonacci(10) # 使用记忆化
def lru_cache():
cache = {}
access_order = []
capacity = 128
def get(key):
if key in cache:
# 移动到最近使用
access_order.remove(key)
access_order.append(key)
return cache[key]
return None
def put(key, value):
if key in cache:
# 更新现有键
access_order.remove(key)
elif len(cache) >= capacity:
# 移除最少使用的
lru_key = access_order.pop(0)
del cache[lru_key]
cache[key] = value
access_order.append(key)
return {"get": get, "put": put}
# 使用示例
cache = lru_cache()
cache["put"](1, 1) # 添加 1
cache["put"](2, 2) # 添加 2
cache["put"](3, 3) # 添加 3
def find_intersection(nums1, nums2):
# 将第一个数组转换为哈希表进行计数
count = {}
for num in nums1:
count[num] = count.get(num, 0) + 1
# 查找交集
result = []
for num in nums2:
if num in count and count[num] > 0:
result.append(num)
count[num] -= 1
return result
find_intersection([1, 2, 2, 1], [2, 2])
def group_anagrams(words):
groups = {}
for word in words:
# 对字符排序以创建键
key = ''.join(sorted(word))
groups.setdefault(key, []).append(word)
return list(groups.values())
group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"])