题目一:
使用数组构建哈希表
提取ASCII码:ord
不能用[[0] for _in range(26)]
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 j in t:
record[ord(j)-ord("a")]-=1
for n in record:
if n !=0:
return False
return True
题目二
使用一个map,存储nums1,使用一个set提取相同元素
if num in table 与 if num in table.keys()相同
删除键值对 del table[num]
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
table={}
for num in nums1:
table[num]=table.get(num,0)+1
# table[num]=1
res=set()
for num in nums2:
if num in table.keys():
res.add(num)
del table[num]
return list(res)
题目三
构建set,防止死循环出现即可。
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
res=set()
while n not in res:
res.add(n)
nums=list(str(n))
nums=[int(i)**2 for i in nums]
n=sum(nums)
if n==1:
return True
return False
题目四
在遍历到每个元素时,查看之前遍历的元素中有没有符合的元素
以数值为key,以索引为value
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
table={}
i=0
for num in nums:
if (target-num) in table.keys():
return [table[target-num],i]
if num not in table:
table[num]=i
i+=1