面试题 04.06. 后继者
面试题 04.06. 后继者
class Solution:
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> Any | None:
if root is None or p is None:
return None
node = root
ans = None
while node:
if node.val <= p.val:
node = node.right
else:
if ans is None or ans.val > node.val:
ans = node
node = node.left
return ans
LCR 088. 使用最小花费爬楼梯
LCR 088. 使用最小花费爬楼梯
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
dp = [0 for i in range(len(cost))]
dp[0], dp[1] = cost[0], cost[1]
for i in range(2, len(cost)):
dp[i] = min(cost[i] + dp[i - 1], cost[i] + dp[i - 2])
return min(dp[-1], dp[-2])
2087. 网格图中机器人回家的最小代价
2087. 网格图中机器人回家的最小代价
class Solution:
def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int:
row_diff = homePos[0] - startPos[0]
col_diff = homePos[1] - startPos[1]
now_pos = startPos
cost = 0
while now_pos != homePos:
if row_diff > 0:
cost += rowCosts[now_pos[0] + 1]
now_pos[0] += 1
row_diff -= 1
elif row_diff < 0:
cost += rowCosts[now_pos[0] - 1]
now_pos[0] -= 1
row_diff += 1
if col_diff > 0:
cost += colCosts[now_pos[1] + 1]
now_pos[1] += 1
col_diff -= 1
elif col_diff < 0:
cost += colCosts[now_pos[1] - 1]
now_pos[1] -= 1
col_diff += 1
return cost
2055. 蜡烛之间的盘子
2055. 蜡烛之间的盘子
import bisect
class Solution:
def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]:
candles_list = []
for i in range(len(s)):
if s[i] == '|':
candles_list.append(i)
answer = []
for item in queries:
start = item[0]
end = item[1]
start = bisect.bisect_left(candles_list, start)
end = bisect.bisect_right(candles_list, end) - 1
if end <= start:
answer.append(0)
else:
answer.append(candles_list[end] - candles_list[start] - 1 - (end - start - 1))
return answer
Comments | NOTHING