题解 | 【模板】滑动窗口

【模板】滑动窗口

https://www.nowcoder.com/practice/be419f584a3f4c5b818833f1ce856626

import java.util.Scanner;
import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(new BufferedInputStream(System.in));
        PrintWriter out = new PrintWriter(System.out);
        int n = in.nextInt();
        int k = in.nextInt();
        int[] nums = new int[n + 1];
        for (int i = 1 ; i <= n; i++) {
            nums[i] = in.nextInt();
        }
        Deque<Integer> queue = new ArrayDeque<>();
        ArrayList<Integer> res = new ArrayList<>();
        for (int i = 1 ; i <= n; i++) {
            //1.
            while (!queue.isEmpty() && i - queue.peekFirst() + 1 > k) {
                queue.pollFirst();
            }
            //2.
            while (!queue.isEmpty() && nums[i] > nums[queue.peekLast()]) {
                queue.pollLast();
            }
            //3.
            queue.offer(i);
            //4.
            if(i >= k) {
                res.add(nums[queue.peekFirst()]);
            }
        }
        res.stream().forEach(item -> {
            out.print(item + " ");
        });
        out.flush();
    }
}

全部评论

相关推荐

鱼专:别投了,我看到有人点了第二个链接投递,还没退出界面,不合适的邮件就发过来了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务