代码随想录算法训练营第六天|242.有效的字母异位词 ● 349. 两个数组的交集 ● 202. 快乐数● 1. 两数之和
学习链接: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解题。其实今天是我第一天学习,加油!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!