242.有效的字母异位词
解法1: hash table
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# method 1
return collections.Counter(s) == collections.Counter(t)
解法2:排序
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# method 2
return sorted(s) == sorted(t)
349. 两个数组的交集
解法1:hash+set
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
dic = {}
res = []
for i in set(nums1):
dic[i] = 1
for j in set(nums2):
if j in dic:
res.append(j)
return res
解法2:set
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
202. 快乐数
解法1:hash set
细节:无限循环是关键,说明是已经存在过的数字,所以可以用set 来查找
class Solution:
def isHappy(self, n: int) -> bool:
def get_number(n):
total = 0
while n:
total += (n % 10)**2
n //= 10
return total
visited = set()
while n != 1 and n not in visited:
visited.add(n)
n = get_number(n)
return n == 1
1. 两数之和
解法1:暴力
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# method 1
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
return [i,j]
解法2:hash
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# method2
dir = {}
for i in range(len(nums)):
if target - nums[i] not in dir:
dir[nums[i]] = i
else:
return [dir[target - nums[i]],i]