150强访谈

滑动窗口最大值

“滑动窗口最大值”问题的详细指南和 Python 实现。

问题陈述

给定一个整数数组 nums 和一个整数 k ,表示滑动窗口的大小,该窗口从数组的最左边移动到最右边。您只能在窗口中看到 k 数字。每次滑动窗口右移一个位置。

返回每个滑动窗口中的最大值。

编写一个函数 maxSlidingWindow(nums: List[int], k: int) -> List[int]

约束条件
  • 1 <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= len(nums)

示例

Example 1
Input
nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
Output
[3, 3, 5, 5, 6, 7]
Explanation

Window [1,3,-1] max=3, [3,-1,-3] max=3, [-1,-3,5] max=5, [-3,5,3] max=5, [5,3,6] max=6, [3,6,7] max=7.

Example 2
Input
nums = [1], k = 1
Output
[1]
Explanation

Single element window, max is 1.

Need a Hint?
考虑使用滑动窗口特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。