LeetCode 题解工作台
找到稳定山的下标
有 n 座山排成一列,每座山都有一个高度。给你一个整数数组 height ,其中 height[i] 表示第 i 座山的高度,再给你一个整数 threshold 。 对于下标不为 0 的一座山,如果它左侧相邻的山的高度 严格 大于 threshold ,那么我们称它是 稳定 的。我们定义下标为 0 …
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们直接从下标为 的山开始遍历,如果它左侧相邻的山的高度大于 ,那么我们就将它的下标加入到结果数组中。 遍历结束后,返回结果数组即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
有 n 座山排成一列,每座山都有一个高度。给你一个整数数组 height ,其中 height[i] 表示第 i 座山的高度,再给你一个整数 threshold 。
对于下标不为 0 的一座山,如果它左侧相邻的山的高度 严格大于 threshold ,那么我们称它是 稳定 的。我们定义下标为 0 的山 不是 稳定的。
请你返回一个数组,包含所有 稳定 山的下标,你可以以 任意 顺序返回下标数组。
示例 1:
输入:height = [1,2,3,4,5], threshold = 2
输出:[3,4]
解释:
- 下标为 3 的山是稳定的,因为
height[2] == 3大于threshold == 2。 - 下标为 4 的山是稳定的,因为
height[3] == 4大于threshold == 2.
示例 2:
输入:height = [10,1,10,1,10], threshold = 3
输出:[1,3]
示例 3:
输入:height = [10,1,10,1,10], threshold = 10
输出:[]
提示:
2 <= n == height.length <= 1001 <= height[i] <= 1001 <= threshold <= 100
解题思路
方法一:遍历
我们直接从下标为 的山开始遍历,如果它左侧相邻的山的高度大于 ,那么我们就将它的下标加入到结果数组中。
遍历结束后,返回结果数组即可。
时间复杂度 ,其中 是数组 的长度。忽略答案数组的空间消耗,空间复杂度 。
class Solution:
def stableMountains(self, height: List[int], threshold: int) -> List[int]:
return [i for i in range(1, len(height)) if height[i - 1] > threshold]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for a clear understanding of array manipulation.
- question_mark
Expect direct application of array-driven solution strategies.
- question_mark
Evaluate for an efficient implementation regarding space and time.
常见陷阱
外企场景- error
Failing to check the condition for the first mountain.
- error
Incorrectly handling the threshold comparison, especially boundary cases.
- error
Not considering edge cases like when no stable mountain exists.
进阶变体
外企场景- arrow_right_alt
Change the threshold dynamically within the array processing.
- arrow_right_alt
Add additional constraints like maximum height or larger input sizes.
- arrow_right_alt
Use a more complex comparison for stability, such as a moving threshold.