学习链接:https://programmercarl.com/哈希表理论基础.html
学习笔记:
遇到“要判断一个值是否在集合中出现过”的问题时,可以考虑hash表。
hash表的形式包括数组、set、dict。当数的位数比较统一、或比较小,可用数组,快;当数的位数可变,可用set;当要同时考虑数的下标和值,可以用dict。
我的解答过程:
242.有效的字母异位词(用的数组作hash表,只需知道字母与‘a’的差,不用知道具体ASCII码)
点击查看代码
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
record=[0]*26
for i in s:
record[ord(i)-ord('a')] += 1
for i in t:
record[ord(i)-ord('a')] -= 1
for i in range(26):
if record[i] != 0:
return False
return True
349.两个数组的交集(用的dict作hash表,结果用set避免重复)
点击查看代码
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
result = set()
hash_dict = {}
for i in nums1:
hash_dict[i]=hash_dict.get(i, 0)+1
for i in nums2:
if i in hash_dict:
result.add(i)
del hash_dict[i]
return list(result)
点击查看代码
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
record=set()
while n not in record:
record.add(n)
new_n = 0
str_n = str(n)
for i in str_n:
new_n += int(i)**2
if new_n == 1:
return True
else:
n = new_n
return False
点击查看代码
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result=dict()
for i, value in enumerate(nums):
if target-value in result:
return [result[target-value], i]
result[value]=i
return []
我都用Python解题。其实今天是我第一天学习,加油!
标签:202,hash,int,随想录,dict,result,return,type,两数 From: https://www.cnblogs.com/tristan241001/p/18443332