● 242.有效的字母异位词
写两个字典然后对比一下就可以。这个纯是享受python比较好写的福利了……
class Solution(object):
def isAnagram(self, s, t):
sDict = self.newDict(s)
tDict = self.newDict(t)
if sDict == tDict:
return True
else:
return False
def newDict(self, str):
mydict = {}
for alpha in str:
if alpha not in mydict:
mydict.update({alpha: 1})
else:
newValue = mydict.get(alpha, 1)
newValue += 1
mydict[alpha] = newValue
return mydict
● 349. 两个数组的交集
有个更简单的写法,不过有点过于简单了,我直接把题解的答案复制过来:
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
我想用字典,并且不用set重新写一遍:
class Solution(object):
def intersection(self, nums1, nums2):
result = []
resultHash = {}
num1Hash = self.getHash(nums1)
num2Hash = self.getHash(nums2)
for num, i in num2Hash.items():
if num in num1Hash and num not in resultHash:
resultHash[num] = 0
result.append(num)
return result
def getHash(self, arr):
myhash = {}
for i in arr:
myhash[i] = 0
return myhash
● 202. 快乐数
通过做这个题,我才知道python的列表也可以用 in 来判断有没有元素,所以有时候哈希表可以用数组来代替(上面有些用键值对写的纯纯浪费空间)
class Solution(object):
def isHappy(self, n):
record = []
while n not in record:
record.append(n)
newnum = 0
numStr = str(n)
for i in numStr:
newnum += int(i)**2
if newnum == 1:
return True
else :
n = newnum
return False
● 1. 两数之和
因为他是力扣第一题,所以成为了每个人入坑必刷,以前不懂,现在懂了怎么写了。结果减其中一个数来判断,这个方法对我这种一根筋的人印象太深了属于是:
class Solution(object):
def twoSum(self, nums, target):
dict = {}
for i, num in enumerate(nums):
complement = target - num
if complement in dict:
return(dict[complement], i)
dict[num] = i
return []