哈希表
散列表(Hash table,也叫哈希表),是根据键(Key)而直接访问在内存储存位置的数据结构。
它通过计算出一个键值的函数(hash function),将所需查询的数据映射到表中一个位置来让人访问,这加快了查找速度。
哈希函数
构造哈希函数方法:
- 直接定址法
- 数字分析法
- 平方取中法
- 折叠法
- 随机数法
- 除留余数法(如下图)
哈希冲突
一个好的哈希函数,应该尽可能的避免冲突
冲突:k1≠k2,而f(k1)=f(k2){\displaystyle k_{1}\neq k_{2}},而{\displaystyle f(k_{1})=f(k_{2})}k1=k2,而f(k1)=f(k2)
解决冲突的方法:
- 开放定址法
- 单独链表法(如上图)
- 再散列
异位词问题
242. 有效的字母异位词
python中的字典即是哈希表,使用字典记录字母出现频次
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
freq = {}
for c in s:
if c in freq:
freq[c] += 1
else:
freq[c] = 1
for c in t:
if c in freq:
freq[c] -= 1
else:
return False
for c in freq:
if freq[c] != 0:
return False
return True
使用列表代替字典,将key转为列表的索引,节省空间
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
freq = [0]*26
for c in s:
freq[ord(c)-ord('a')] += 1
for c in t:
freq[ord(c)-ord('a')] -= 1
for c in freq:
if c!=0:
return False
return True
49. 字母异位词分组
由于互为字母异位词的两个字符串包含的字母相同,因此两个字符串中的相同字母出现的次数一定是相同的, 故可以将每个字母出现的次数使用字符串表示,作为哈希表的键。
class Solution:
def groupAnagrams(self, strs):
res_dict = collections.defaultdict(list)
for s in strs:
key = [0] * 26
# 类似于前面的字典,例表的索引作为key
for c in s:
key[ord(c) - ord("a")] += 1
res_dict[tuple(key)].append(s)
return list(res_dict.values())