LC242.有效的字母异位词:
if len(s) != len(t):
return False
countS, countT = {}, {}
for i in range(len(s)):
countS[s[i]] = 1 + countS.get(s[i], 0)
countT[t[i]] = 1 + countT.get(t[i], 0)
return countS == countT
哈希表好解,定义两个哈希表,然后在s中遍历i。将i加入不同的集合最后再比较是否相等。
LC349. 两个数组的交集:
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list (set(nums1) & set(nums2))
两个数组先变成集合,求交集后还原为数组
LC202 快乐数:
class Solution:
def isHappy(self, n: int) -> bool:
sum_ = 0
# 从个位开始依次取,平方求和
while num:
sum_ += (num % 10) ** 2
num = num // 10
return sum_
# 记录中间结果
record = set()
while True:
n = calculate_happy(n)
if n == 1:
return True
# 如果中间结果重复出现,说明陷入死循环了,该数不是快乐数
if n in record:
return False
else:
record.add(n)
LC 1两数之和:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
res = {}
n = len(nums)
for i in range(n):
if target - nums[i] in res:
return [i, res[target-nums[i]]]
else:
res[nums[i]] = i
return []
本文精选了LeetCode上的几个经典算法题目,包括有效的字母异位词、两个数组的交集、快乐数及两数之和等问题,通过示例代码详细介绍了如何使用Python高效解决这些算法挑战。

被折叠的 条评论
为什么被折叠?



