当前位置: 首页 > news >正文

59 - I. 滑动窗口的最大值


comments: true
difficulty: 简单
edit_url: https://github.com/doocs/leetcode/edit/main/lcof/%E9%9D%A2%E8%AF%95%E9%A2%9859%20-%20I.%20%E6%BB%91%E5%8A%A8%E7%AA%97%E5%8F%A3%E7%9A%84%E6%9C%80%E5%A4%A7%E5%80%BC/README.md

面试题 59 - I. 滑动窗口的最大值

题目描述

给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。

示例:

输入: nums= [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7] 

解释: 
滑动窗口的位置                最大值
---------------               -----
[1  3  -1] -3  5  3  6  7       31 [3  -1  -3] 5  3  6  7       31  3 [-1  -3  5] 3  6  7       51  3  -1 [-3  5  3] 6  7       51  3  -1  -3 [5  3  6] 7       61  3  -1  -3  5 [3  6  7]      7

 

提示:

你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。

注意:本题与主站 239 题相同:https://leetcode.cn/problems/sliding-window-maximum/

解法

方法一:单调队列

单调队列常见模型:找出滑动窗口中的最大值/最小值。模板:

q = deque()
for i in range(n):# 判断队头是否滑出窗口while q and checkout_out(q[0]):q.popleft()while q and check(q[-1]):q.pop()q.append(i)

时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( k ) O(k) O(k)。其中 n n n 为数组长度。

Python3
class Solution:def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:q = deque()ans = []for i, x in enumerate(nums):#入:队尾小于新元素,将不可能成为新窗口最大值【左->右:维护窗口递减队列】while q and nums[q[-1]] <= x:q.pop()q.append(i)#出:大于窗口大小if q and i - q[0] + 1 > k:q.popleft()#记录结果if i >= k - 1:ans.append(nums[q[0]])return ans
Java
class Solution {public int[] maxSlidingWindow(int[] nums, int k) {int n = nums.length;int[] ans = new int[n - k + 1];Deque<Integer> q = new ArrayDeque<>();for (int i = 0; i < n; ++i) {if (!q.isEmpty() && i - q.peek() + 1 > k) {q.poll();}while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) {q.pollLast();}q.offer(i);if (i >= k - 1) {ans[i - k + 1] = nums[q.peek()];}}return ans;}
}
C++
class Solution {
public:vector<int> maxSlidingWindow(vector<int>& nums, int k) {vector<int> ans;deque<int> q;int n = nums.size();for (int i = 0; i < n; ++i) {if (!q.empty() && i - q.front() + 1 > k) {q.pop_front();}while (!q.empty() && nums[q.back()] <= nums[i]) {q.pop_back();}q.push_back(i);if (i >= k - 1) {ans.push_back(nums[q.front()]);}}return ans;}
};
Go
func maxSlidingWindow(nums []int, k int) (ans []int) {q := []int{}for i, x := range nums {for len(q) > 0 && i-q[0]+1 > k {q = q[1:]}for len(q) > 0 && nums[q[len(q)-1]] <= x {q = q[:len(q)-1]}q = append(q, i)if i >= k-1 {ans = append(ans, nums[q[0]])}}return
}
TypeScript
function maxSlidingWindow(nums: number[], k: number): number[] {const q: number[] = [];const n = nums.length;const ans: number[] = [];for (let i = 0; i < n; ++i) {while (q.length && i - q[0] + 1 > k) {q.shift();}while (q.length && nums[q[q.length - 1]] <= nums[i]) {q.pop();}q.push(i);if (i >= k - 1) {ans.push(nums[q[0]]);}}return ans;
}
Rust
use std::collections::VecDeque;
impl Solution {pub fn max_sliding_window(nums: Vec<i32>, k: i32) -> Vec<i32> {let k = k as usize;let n = nums.len();let mut ans = vec![0; n - k + 1];let mut q = VecDeque::new();for i in 0..n {while !q.is_empty() && i - q[0] + 1 > k {q.pop_front();}while !q.is_empty() && nums[*q.back().unwrap()] <= nums[i] {q.pop_back();}q.push_back(i);if i >= k - 1 {ans[i - k + 1] = nums[q[0]];}}ans}
}
JavaScript
/*** @param {number[]} nums* @param {number} k* @return {number[]}*/
var maxSlidingWindow = function (nums, k) {const q = [];const n = nums.length;const ans = [];for (let i = 0; i < n; ++i) {while (q.length && i - q[0] + 1 > k) {q.shift();}while (q.length && nums[q[q.length - 1]] <= nums[i]) {q.pop();}q.push(i);if (i >= k - 1) {ans.push(nums[q[0]]);}}return ans;
};
C#
public class Solution {public int[] MaxSlidingWindow(int[] nums, int k) {if (nums.Length == 0) {return new int[]{};}int[] array = new int[nums.Length - (k - 1)];Queue<int> queue = new Queue<int>();int index = 0;for (int i = 0; i < nums.Length; i++) {queue.Enqueue(nums[i]);if (queue.Count == k) {array[index] = queue.Max();queue.Dequeue();index++;}}return array;}
}
Swift
class Solution {func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] {let n = nums.countvar ans = [Int]()var deque = [Int]()for i in 0..<n {if !deque.isEmpty && deque.first! < i - k + 1 {deque.removeFirst()}while !deque.isEmpty && nums[deque.last!] <= nums[i] {deque.removeLast()}deque.append(i)if i >= k - 1 {ans.append(nums[deque.first!])}}return ans}
}

http://www.mrgr.cn/news/25513.html

相关文章:

  • Linux 三种方式查看和设置主机名
  • OpenStack创建快照原理
  • JMM 指令重排 volatile happens-before
  • shader 案例学习笔记之偏移
  • 【时时三省】c语言例题----华为机试题<进制转换>
  • Java11环境安装(Windows)
  • 学习Vue3的第五天
  • 使用dnSpy调试服务端IIS部署的WebService的程序集
  • Java重修笔记 第五十四天 坦克大战(四)多线程基础
  • 大模型微调 - 用PEFT来配置和应用 LoRA 微调
  • C语言初识编译和链接
  • [M二分答案] lc2576. 求出最多标记下标(二分答案+同向双指针+贪心)
  • 操作系统 ---- 处理机调度
  • 配环境时的一些记录
  • 【Colab代码调试】End-to-end reproducible AI pipelines in radiology using the cloud
  • Vue: 创建vue项目
  • Win32编程:创建属于你的第一个窗口
  • 贪心算法day30|452. 用最少数量的箭引爆气球(排序+多重叠的处理)、435. 无重叠区间(去除哪个才是最优)、763. 划分字母区间(类阿斯克码换算)
  • 《JavaEE进阶》----16.<Mybatis简介、操作步骤、相关配置>
  • 大模型干货 | 如何使用Unsloth框架对Llama进行微调?