#LC242 有效的字母异位词
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
record = [0]*26
for word in s:
record[ord(word) - ord("a")] += 1
for word in t:
record[ord(word) - ord("a")] -= 1
for i in range(len(record)):
if record[i] != 0:
return False
return True
##### 其他两种使用python默认collections库中实现的数据结构
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
from collections import defaultdict
s_dict = defaultdict(int)
t_dict = defaultdict(int)
for x in s:
s_dict[x] += 1
for x in t:
t_dict[x] += 1
return s_dict == t_dict
####
class Solution(object):
def isAnagram(self, s: str, t: str) -> bool:
from collections import Counter
a_count = Counter(s)
b_count = Counter(t)
return a_count == b_count
数组就是一个简单的哈希表,本题中至多只有26个不同元素,那么索引就是数组的默认索引而其中的元素便是各个字母出现的次数。同时还可以使用两种collections库中内置的函数实现(这两种方式更像是使用字典)。
##LC349 两个数组的交集
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
table = {}
for num in nums1:
table[num] = table.get(num, 0) + 1
# 使用集合存储结果
res = set()
for num in nums2:
if num in table:
res.add(num)
del table[num]
return list(res)
### 使用set()直接对两个列表进行比对
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
直接使用python内部自带set很容易解决,同时还可以使用dict也就是{}字典来实现,但是要注意字典的无初值赋值操作以及删除操作。
##LC 202. 快乐数
class Solution:
def isHappy(self, n: int) -> bool:
record = set()
while n not in record:
record.add(n)
new_num = 0
n = str(n)
for i in n:
new_num += int(i)**2
if new_num == 1 :
return True
else: n = new_num
return False
##### 第二种方法更多是对于数值计算的考量 ,其中的divmod函数是使用的关键。
class Solution:
def isHappy(self, n: int) -> bool:
record = set()
while True:
n = self.get_sum(n)
if n == 1:
return True
# 如果中间结果重复出现,说明陷入死循环了,该数不是快乐数
if n in record:
return False
else:
record.add(n)
def get_sum(self,n: int) -> int:
new_num = 0
while n:
n, r = divmod(n, 10)
new_num += r ** 2
return new_num
看似很复杂,实则是对终止条件的判断,由于无限循环的存在,大胆判断终止条件为new_num的复现,所以使用set来存储中间过程。
##LC1 两数之和
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
records = dict()
for index,num in enumerate(nums):
if target-num in records:
return [records[target-num],index]
records[num] = index
return False
使用dict的特性,将数值作为索引,将在原列表中的位置作为对应值填入字典之中,根据对索引的查询完成位置定位。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = set()
for i,num in enumerate(nums):
complement = target-num
if complement in seen:
return [nums.index(complement),i]
seen.add(num)
可以使用集合来存储数字,使用index方法来实现对于位置的索引,总结就是空间换时间。要去了解python中列表、集合、字典的实现方式,暂时猜测和哈希表有关(?),比如index函数的使用。