242 判断异位词
思路:首先判断两个词的长度是否相等, 如不相等,返回false。然后建立一个空白的hash map,用来储存每个词中各个字母和它出现的次数。如相同返回true,否则为false
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
countMap = {}
for char in s:
countMap[char] = countMap.get(char, 0) + 1
for char in t:
countMap[char] = countMap.get(char, 0) - 1
for count in countMap.values():
if count != 0:
return False
return True
349 两个数组的交集
思路:利用Hash set中所有元素唯一性的特性,建立一个空白的hash set,用来储存交集的元素。第一遍先遍历nums1,并将其所有的值储存进set的value中。第二遍遍历nums2,检查其元素是否在set中出现,如出现则保留该元素。最后将set转化为list输出。
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
tempSet = set()
resultSet = set()
for i in nums1:
tempSet.add(i)
for j in nums2:
if j in tempSet:
resultSet.add(j)
return list(resultSet)
202 快乐数
- 将给定的数转换为字符串,方便逐位提取数字。
- 创建一个空的哈希集合 visited,用于记录已经计算过的数字。
- 进入循环,直到出现以下情况:
- 当前数字为 1,说明是快乐数,返回 True。
- 当前数字在 visited 中出现过,说明进入了循环无法终止的情况,返回 False。
- 否则,将当前数字加入 visited 中,并计算下一个数字。
- 将当前数字转换为字符串,逐位提取数字,计算各位数字的平方和。
- 更新当前数字为平方和。
- 返回 False,表示不是快乐数。
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
visited = set()
while n != 1 and n not in visited:
visited.add(n)
n = sum(int(i) ** 2 for i in str(n))
return n == 1