6152. 赢得比赛需要的最少训练时长
https://leetcode.cn/problems/minimum-hours-of-training-to-win-a-competition/
模拟
补充到刚好能打过敌人就可以了。
class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
ans = 0
curHp = initialEnergy
curExp = initialExperience
for hp, exp in zip(energy, experience):
if curHp <= hp:
ans += hp - curHp + 1
curHp = hp + 1
curHp -= hp
if curExp <= exp:
ans += exp - curExp + 1
curExp = exp + 1
curExp += exp
return ans
6166. 最大回文数字
https://leetcode.cn/problems/largest-palindromic-number/
贪心&模拟
class Solution:
def largestPalindromic(self, num: str) -> str:
# 先存入hash
hashMap = [0] * 10
for x in num:
hashMap[int(x)] += 1
# 全 0 的时候特判
if hashMap[0] == len(num):
return '0'
ans = ''
# 先选大的, 0 最后处理
for i in range(9, 0, -1):
if hashMap[i] >= 2:
ans += str(i) * (hashMap[i] // 2)
# 如果已经加入数字,可以填入 0
if len(ans) != 0:
ans += '0' * (hashMap[0] // 2)
# 找剩下的最大数放中间
for i in range(9, -1, -1):
if hashMap[i] % 2 == 1:
ans += str(i) + ans[::-1]
break
else:
ans += ans[::-1]
return ans
6154. 感染二叉树需要的总时间
https://leetcode.cn/problems/amount-of-time-for-binary-tree-to-be-infected/
DFS 建图 + BFS 遍历
建图后找出离起始节点最远的距离:
class Solution:
def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
parents = {}
def dfs(node: Optional[TreeNode], pa: Optional[TreeNode]) -> None:
if node is None: return
if node.val == start: self.start = node
parents[node] = pa
dfs(node.left, node)
dfs(node.right, node)
dfs(root, None)
ans = -1
vis = {None, self.start}
q = [self.start]
while q:
ans += 1
tmp = q
q = []
for node in tmp:
for x in [node.left, node.right, parents[node]]:
if x not in vis:
vis.add(x)
q.append(x)
return ans
6155. 找出数组的第 K 大和
https://leetcode.cn/problems/find-the-k-sum-of-an-array/
还没搞懂,有时间填坑。