返回
LeetCode Weekly Contest 255:独特解题视角,深挖算法精髓
闲谈
2024-01-22 15:30:18
在 LeetCode Weekly Contest 255 中,算法爱好者们再次齐聚一堂,共同切磋技艺。本次比赛的题目虽看似简单,却暗藏玄机,需要选手们仔细思考,方能破解谜题。让我们一探究竟,领略这些解题思路的独特魅力。
NO.1 找出数组的最大公约数
解题思路: 辗转相除法求最大公约数。
代码展示:
def findGcd(nums):
"""
:type nums: List[int]
:rtype: int
"""
gcd = nums[0]
for num in nums[1:]:
while num:
gcd, num = num, gcd % num
return gcd
NO.2 找出不同的二进制字符串
解题思路: 暴力枚举即可,为了方便枚举,可以将二进制字符串解析成整数。
代码展示:
def findDifferentBinaryString(nums):
"""
:type nums: List[str]
:rtype: str
"""
n = len(nums)
for i in range(1 << n):
binary_str = bin(i)[2:]
binary_str = '0' * (n - len(binary_str)) + binary_str
if binary_str not in nums:
return binary_str
NO.3 检查字符串是否可以通过删除某些字符变成回文串
解题思路: 利用回文串的特性,从两端向中间比较字符是否相同。
代码展示:
def canBePalindrome(s):
"""
:type s: str
:rtype: bool
"""
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
NO.4 找出符合条件的子树数量
解题思路: 使用深度优先搜索,计算每个子树的和,并根据条件判断是否符合要求。
代码展示:
def countSubTrees(n, edges, labels):
"""
:type n: int
:type edges: List[List[int]]
:type labels: List[int]
:rtype: List[int]
"""
graph = [[] for _ in range(n)]
for edge in edges:
graph[edge[0]].append(edge[1])
graph[edge[1]].append(edge[0])
res = [0] * n
def dfs(node, parent):
count = [0] * 21 # 统计每个节点子树中标签的出现次数
count[labels[node]] += 1
for adj in graph[node]:
if adj != parent:
cnt = dfs(adj, node)
for i in range(21):
count[i] += cnt[i]
if count[labels[node]] == 1:
res[node] = 1
return count
dfs(0, -1)
return res
通过这些解题思路,我们可以领略到算法之美。算法不仅是解题工具,更是一种思维方式,可以帮助我们培养严谨的逻辑思维和解决问题的能力。让我们继续探索算法的奥秘,在代码的世界里尽情驰骋。