DAY 6 代码随想录刷题
哈希表解题
哈希表是用来快速判断一个元素是否出现集合里
242.有效的字母异位词
使用哈希思路求解即可,不需要记入ASCII码,使用一个26位数组遍历即可,dic[s[i] - ‘a’],先遍历s递增再遍历t递减,最后判断每个字符是否为0即可
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
#哈希法,数组也是哈希表
#哈希表都是用来快速判断一个元素是否出现集合里
hash = [0]*26
for i in s:
hash[ord(i) - ord("a")] += 1 #统计s中每个字母出现的次数
for i in t:
hash[ord(i) - ord("a")] -= 1 #统计t中每个字母出现的次数,并减去该次数。
#如果s和t满足字母异位词,则此时hash数组中的值全为0
for i in range(26):
if hash[i] != 0: return False
return True
349. 两个数组的交集 :构造一个哈希表进行交集求解
#使用字典和集合
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
table = {} #建立空的哈希表
res = set()
for num in nums1:
table[num] = table.get(num,0) + 1
for num in nums2:
if num in table:
res.add(num)
del table[num] #从哈希表删除num,目的是防止输出中有重复
return list(res)
###使用数组
class Solution:
def intersection(self, nums1, nums2):
count1 = [0]*1001
count2 = [0]*1001
result = []
for i in range(len(nums1)):
count1[nums1[i]]+=1
for j in range(len(nums2)):
count2[nums2[j]]+=1
for k in range(1001):
if count1[k]*count2[k]>0:
result.append(k)
return result
202. 快乐数:根据题意进行数字的变化,将新数字放入哈希表,有重复元素则表示存在环
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
record = set()
while True:
n = self.get_sum(n)
if n == 1:
return True
# 如果中间结果重复出现,说明陷入死循环了,该数不是快乐数
if n in record:
return False
else:
record.add(n)
def get_sum(self,n):
new_num = 0
while n:
n, r = divmod(n, 10)
new_num += r ** 2
return new_num
1. 两数之和 :边循环边构造哈希表即可
题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
思路
构建空的哈希表(字典),然后将整数数组 nums的值nums[i]遍历,判断target-nums[i]其是否在哈希表中,不在的话就添加到表里,然后循环,如果判断条件成立,说明找到符合条件的整数。
代码
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hash = dict()
for i in range(len(nums)):
if target - nums[i] in hash:
return [hash[target-nums[i]],i]
hash[nums[i]] = i
return []