LeetCode 题解工作台
长度为 K 的子数组的能量值 I
给你一个长度为 n 的整数数组 nums 和一个正整数 k 。 一个数组的 能量值 定义为: 如果 所有 元素都是依次 连续 且 上升 的,那么能量值为 最大 的元素。 否则为 -1 。 你需要求出 nums 中所有长度为 k 的 子数组 的能量值。 请你返回一个长度为 n - k + 1 的整数数…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 滑动窗口(状态滚动更新)
答案摘要
我们定义一个数组 ,其中 表示以第 个元素结尾的连续上升子序列的长度。初始时 $f[i] = 1$。 接下来,我们遍历数组 ,计算数组 的值。如果 $nums[i] = nums[i - 1] + 1$,则 $f[i] = f[i - 1] + 1$;否则 $f[i] = 1$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路
题目描述
给你一个长度为 n 的整数数组 nums 和一个正整数 k 。
一个数组的 能量值 定义为:
- 如果 所有 元素都是依次 连续 且 上升 的,那么能量值为 最大 的元素。
- 否则为 -1 。
你需要求出 nums 中所有长度为 k 的 子数组 的能量值。
请你返回一个长度为 n - k + 1 的整数数组 results ,其中 results[i] 是子数组 nums[i..(i + k - 1)] 的能量值。
示例 1:
输入:nums = [1,2,3,4,3,2,5], k = 3
输出:[3,4,-1,-1,-1]
解释:
nums 中总共有 5 个长度为 3 的子数组:
[1, 2, 3]中最大元素为 3 。[2, 3, 4]中最大元素为 4 。[3, 4, 3]中元素 不是 连续的。[4, 3, 2]中元素 不是 上升的。[3, 2, 5]中元素 不是 连续的。
示例 2:
输入:nums = [2,2,2,2,2], k = 4
输出:[-1,-1]
示例 3:
输入:nums = [3,2,3,2,3,2], k = 2
输出:[-1,3,-1,3,-1]
提示:
1 <= n == nums.length <= 5001 <= nums[i] <= 1051 <= k <= n
解题思路
方法一:递推
我们定义一个数组 ,其中 表示以第 个元素结尾的连续上升子序列的长度。初始时 。
接下来,我们遍历数组 ,计算数组 的值。如果 ,则 ;否则 。
然后,我们在 的范围内遍历数组 ,如果 ,那么答案数组添加 ,否则添加 。
遍历结束后,返回答案数组。
时间复杂度 ,空间复杂度 。其中 表示数组 的长度。
class Solution:
def resultsArray(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
f = [1] * n
for i in range(1, n):
if nums[i] == nums[i - 1] + 1:
f[i] = f[i - 1] + 1
return [nums[i] if f[i] >= k else -1 for i in range(k - 1, n)]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Can the candidate efficiently implement the sliding window technique without recalculating values from scratch?
- question_mark
Does the candidate understand the importance of maintaining running state to optimize performance?
- question_mark
How well does the candidate manage the sliding window, especially with regard to duplicate elements?
常见陷阱
外企场景- error
Failing to handle subarrays with duplicate elements correctly, leading to incorrect results for those subarrays.
- error
Using a brute force method with nested loops that results in excessive time complexity, especially for larger inputs.
- error
Not optimizing the update of the sliding window, causing unnecessary recalculations of maximum and minimum values.
进阶变体
外企场景- arrow_right_alt
Find the power of k-size subarrays where the elements must satisfy a different condition, such as being strictly increasing.
- arrow_right_alt
Adapt the solution to handle dynamic input sizes, where the value of k changes as the problem progresses.
- arrow_right_alt
Consider optimizing the solution by using a deque to keep track of the minimum and maximum values in the sliding window.