Python算法学习 - 哈希表
哈希表学习及其应用
哈希表(hash table)作为数据结构中非常重要的一环,在算法题的解法中也频频需要用到。而Python的内置数据结构 - 字典,就是用哈希表的原理实现的。
哈希表是什么
(来源wikipedia)散列表(Hash table,也叫哈希表),是根据键(Key)而直接访问在記憶體儲存位置的数据结构。 也就是说,它通过计算一个关于键值的函数,将所需查询的数据映射到表中一个位置来访问记录,这加快了查找速度。 这个映射函数称做散列函数,存放记录的数组称做散列表。
哈希表的优势
哈希表在查询时拥有极其快的速度,在有需要建立索引的需求时拥有极高的效率。
Python实现哈希表
class hashTable:
def __init__(self):
self.items = []
pass
def add(self, key, value):
self.items.append((key, value))
def get(self, key):
for item in self.items:
if item[0] == key:
return item[1] # 返回匹配到的第一个值
print('所查找的键不存在')
例题
来源LeetCode
计算可以构成回旋镖的点的数量。
class Solution:
def numberOfBoomerangs(self, points: List[List[int]]) -> int:
distance = {}
def calDistance(a, b):
d1 = a[0] - b[0]
d2 = a[1] - b[1]
return d1 ** 2 + d2 ** 2
for i in range(len(points)):
temp = points.pop(0)
distance[i] = {}
for point in points:
d = calDistance(temp, point)
if d not in distance[i].keys():
distance[i][d] = 1
else:
distance[i][d] += 1
points.append(temp)
# 计算最后结果
ans = 0
for k, v in distance.items():
for k1, v1 in v.items():
if v1 > 1:
ans += v1 * (v1-1)
return ans
时间复杂度为O(
N
2
N^2
N2)
空间复杂度为O(
N
2
N^2
N2)
空间复杂度有待改进。