哈希表
什么是哈希表:可以简单理解为一组数字!通过所以下标来访问数据,只不过它的索引经过哈希处理了得到的下标!(这是大白话的理解,详细解析可以自己搜一下)
比较关键的一部份是哈希冲突:
拉链法
刚刚小李和小王在索引1的位置发生了冲突,发生冲突的元素都被存储在链表中。 这样我们就可以通过索引找到小李和小王了
(数据规模是dataSize, 哈希表的大小为tableSize)
其实拉链法就是要选择适当的哈希表的大小,这样既不会因为数组空值而浪费大量内存,也不会因为链表太长而在查找上浪费太多时间。
#线性探测法
使用线性探测法,一定要保证tableSize大于dataSize。 我们需要依靠哈希表中的空位来解决碰撞问题。
例如冲突的位置,放了小李,那么就向下找一个空位放置小王的信息。所以要求tableSize一定要大于dataSize ,要不然哈希表上就没有空置的位置来存放 冲突的数据了。如图所示:
242. 有效的字母异位词
思路:使用字典来做,key是字母,value是出现的次数
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
dict1 = {}
for str1 in s:
# 这里需要判断一下,直接++是会报错的!
if str1 in dict1:
dict1[str1] += 1
else:
dict1[str1] = 1
for str_t in t:
if str_t in dict1:
dict1[str_t] -= 1
else:
return False
for key in dict1:
if dict1[key] == 0:
continue
else:
return False
return True
349. 两个数组的交集
思路:使用Python自带的集合来做!或者使用哈希表有出现的就添加到列表中去
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
set_1 = set(nums1)
set_2 = set(nums2)
list_res = list(set_1 & set_2)
return list_res
202. 快乐数
思路:关键的是如果不是快乐数,那么平方和必定会出现重复的一个数
题目中说了会 无限循环,那么也就是说求和的过程中,sum会重复出现,这对解题很重要!
class Solution:
def isHappy(self, n: int) -> bool:
temp = n
set_n = set()
while temp != 1:
if temp in set_n:
return False
else:
# 把每次数都添加到集合中去
set_n.add(temp)
temp_sum = temp
temp = 0
while temp_sum:
temp1 = temp_sum % 10
temp += temp1 * temp1
temp_sum = temp_sum // 10
# set_n.add(temp)
return True
思路:就是使用哈希表来做!
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
res = []
dict_nums = {}
for index,value in enumerate(nums):
if target - value in dict_nums:
index1 = dict_nums[target - value]
res.append(index1)
res.append(index)
else:
dict_nums[value] = index
return res