LeetCode 题解工作台
新增的最少台阶数
给你一个 严格递增 的整数数组 rungs ,用于表示梯子上每一台阶的 高度 。当前你正站在高度为 0 的地板上,并打算爬到最后一个台阶。 另给你一个整数 dist 。每次移动中,你可以到达下一个距离你当前位置(地板或台阶) 不超过 dist 高度的台阶。当然,你也可以在任何正 整数 高度处插入尚不…
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
根据题目描述,我们知道,每一次计划爬上一个新的台阶,都需要满足新的台阶的高度与当前所在位置的高度之差不超过 `dist`,否则,我们需要贪心地在距离当前位置 的地方插入一个新的台阶,爬上一个新的台阶,一共需要插入的台阶数为 $\lfloor \frac{b - a - 1}{dist} \rfloor$,其中 和 分别为当前位置和新台阶的高度。那么答案即为所有插入的台阶数之和。 时间复杂度 …
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个 严格递增 的整数数组 rungs ,用于表示梯子上每一台阶的 高度 。当前你正站在高度为 0 的地板上,并打算爬到最后一个台阶。
另给你一个整数 dist 。每次移动中,你可以到达下一个距离你当前位置(地板或台阶)不超过 dist 高度的台阶。当然,你也可以在任何正 整数 高度处插入尚不存在的新台阶。
返回爬到最后一阶时必须添加到梯子上的 最少 台阶数。
示例 1:
输入:rungs = [1,3,5,10], dist = 2 输出:2 解释: 现在无法到达最后一阶。 在高度为 7 和 8 的位置增设新的台阶,以爬上梯子。 梯子在高度为 [1,3,5,7,8,10] 的位置上有台阶。
示例 2:
输入:rungs = [3,6,8,10], dist = 3 输出:0 解释: 这个梯子无需增设新台阶也可以爬上去。
示例 3:
输入:rungs = [3,4,6,7], dist = 2 输出:1 解释: 现在无法从地板到达梯子的第一阶。 在高度为 1 的位置增设新的台阶,以爬上梯子。 梯子在高度为 [1,3,4,6,7] 的位置上有台阶。
示例 4:
输入:rungs = [5], dist = 10 输出:0 解释:这个梯子无需增设新台阶也可以爬上去。
提示:
1 <= rungs.length <= 1051 <= rungs[i] <= 1091 <= dist <= 109rungs严格递增
解题思路
方法一:贪心 + 模拟
根据题目描述,我们知道,每一次计划爬上一个新的台阶,都需要满足新的台阶的高度与当前所在位置的高度之差不超过 dist,否则,我们需要贪心地在距离当前位置 的地方插入一个新的台阶,爬上一个新的台阶,一共需要插入的台阶数为 ,其中 和 分别为当前位置和新台阶的高度。那么答案即为所有插入的台阶数之和。
时间复杂度 ,其中 为 rungs 的长度。空间复杂度 。
class Solution:
def addRungs(self, rungs: List[int], dist: int) -> int:
rungs = [0] + rungs
return sum((b - a - 1) // dist for a, b in pairwise(rungs))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Checks if the candidate identifies the greedy pattern and gap-based approach.
- question_mark
Looks for correct calculation of added rungs without over-insertion.
- question_mark
Observes awareness of strictly increasing constraint and maximum distance invariant.
常见陷阱
外企场景- error
Failing to handle the gap from the floor to the first rung properly.
- error
Using floor division instead of ceiling, causing undercount of needed rungs.
- error
Not updating the current position after adding intermediate rungs, violating the distance constraint.
进阶变体
外企场景- arrow_right_alt
Allow non-strictly increasing rungs and compute minimal insertions to maintain non-decreasing order within dist.
- arrow_right_alt
Use variable distance limits for each rung transition instead of a fixed dist.
- arrow_right_alt
Determine the minimal total height of added rungs instead of the count of rungs.