LeetCode 题解工作台

新增的最少台阶数

给你一个 严格递增 的整数数组 rungs ,用于表示梯子上每一台阶的 高度 。当前你正站在高度为 0 的地板上,并打算爬到最后一个台阶。 另给你一个整数 dist 。每次移动中,你可以到达下一个距离你当前位置(地板或台阶) 不超过 dist 高度的台阶。当然,你也可以在任何正 整数 高度处插入尚不…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

根据题目描述,我们知道,每一次计划爬上一个新的台阶,都需要满足新的台阶的高度与当前所在位置的高度之差不超过 `dist`,否则,我们需要贪心地在距离当前位置 的地方插入一个新的台阶,爬上一个新的台阶,一共需要插入的台阶数为 $\lfloor \frac{b - a - 1}{dist} \rfloor$,其中 和 分别为当前位置和新台阶的高度。那么答案即为所有插入的台阶数之和。 时间复杂度 …

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 严格递增 的整数数组 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 <= 105
  • 1 <= rungs[i] <= 109
  • 1 <= dist <= 109
  • rungs 严格递增
lightbulb

解题思路

方法一:贪心 + 模拟

根据题目描述,我们知道,每一次计划爬上一个新的台阶,都需要满足新的台阶的高度与当前所在位置的高度之差不超过 dist,否则,我们需要贪心地在距离当前位置 distdist 的地方插入一个新的台阶,爬上一个新的台阶,一共需要插入的台阶数为 ba1dist\lfloor \frac{b - a - 1}{dist} \rfloor,其中 aabb 分别为当前位置和新台阶的高度。那么答案即为所有插入的台阶数之和。

时间复杂度 O(n)O(n),其中 nnrungs 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
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))
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

新增的最少台阶数题解:贪心·invariant | LeetCode #1936 中等