哈希表
- 也叫散列表 根据关键码值 而进行访问的数据结构
- 通过将关键码值 映射到表中的一个位置来访问记录,以加快查找的速度
- 哈希函数:将存储的值 映射到一个index
哈希碰撞
- 如果多个元素计算出同一个关键码值,将数据存放到一个链表
总结
阅读hashmap源码 写一个关于 HashMap 的小总结。 说明:对于不熟悉 Java 语言的同学,此项作业可选做。
相关练习题
01 两数之和
# 思路 两遍hashtable
def twoSum(self, nums, target):
hashmap = dict()
for index, value in enumerate(nums):
hashmap[value] = index
for i in range(len(nums)):
j = target - nums[i]
if j in hashmap.keys():
if i != hashmap[j]:
return i, hashmap[j]
def twoSum2(self, nums, target):
hashmap = dict()
for i, value in enumerate(nums):
j = target - nums[i]
if j in hashmap.keys():
if i != hashmap[j]:
return i, hashmap[j]
else:
hashmap[value] = i
def twoSum3(self, nums, target):
for index in range(len(nums)):
if target - nums[index] in nums:
index1 = nums.index(target - nums[index])
if index1 != index:
return [index, index1]
242 有效的字母异位
思路: hashtable 记录每个字符串中字符出现的次数
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
str1_dict = dict()
for index in range(len(s)):
if s[index] in str1_dict.keys():
str1_dict[s[index]] += 1
else:
str1_dict[s[index]] = 1
str2_dict = dict()
for index in range(len(t)):
if t[index] in str2_dict.keys():
str2_dict[t[index]] += 1
else:
str2_dict[t[index]] = 1
if str2_dict == str1_dict:
return True
else:
return False
49 字母异位词分组
思路:先排序 再hashtable
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
res_dict = dict()
for line in strs:
new_line = sorted(line)
new_line = "".join(new_line)
if new_line not in res_dict.keys():
res_dict[new_line] = list()
res_dict[new_line].append(line)
res_lst = list()
for value in res_dict.values():
res_lst.append(value)
return res_lst