zoukankan      html  css  js  c++  java
  • 滑动窗口模板题(对读写性能要求贼高)

    7、滑动窗口模板题

    题目链接:

    https://www.acwing.com/problem/content/156/

    题解:

    做滑动窗口,一般先假想成普通队列来做,再分析题目的单调性,改进优化

    AC代码:

    import java.util.*;
    import java.io.*;
    
    public class Main {
        public static void main(String[] args) throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
            // 对输入数据进行初始化
            String[] s1 = reader.readLine().split(" ");
            int n = Integer.parseInt(s1[0]);
            int k = Integer.parseInt(s1[1]);
            int[] a = new int[n], q = new int[n];
            String[] s = reader.readLine().split(" ");
            for (int i = 0; i < n; i++)
                a[i] = Integer.parseInt(s[i]);
            
            int hh = 0, ee = -1;
            for(int i = 0;i < n;i ++) {
                while(hh <= ee && q[hh] < i - k + 1) hh++;
                while(hh <= ee && a[q[ee]] >= a[i] ) ee--;
                q[++ee] = i;
                if(i >= k - 1) log.write(a[q[hh]] + " ");
            }
            log.write("
    ");
            hh = 0; ee = -1;
            for(int i = 0;i < n;i ++) {
                while(hh <= ee && q[hh] < i - k + 1) hh++;
                while(hh <= ee && a[q[ee]] <= a[i] ) ee--;
                q[++ee] = i;
                if(i >= k - 1) log.write(a[q[hh]] + " ");
            }
            
            // 关闭输入输出流
            log.flush(); // 如果不flush,没有标准输出
            reader.close();
            log.close();
        }
    }
    
  • 相关阅读:
    mode
    文件操作
    深浅拷贝
    基础数据类型补充
    再谈编码 decode和encode
    Python练习题 015:一颗自由落地的球
    Python练习题 014:完数
    Python练习题 013:求解a+aa+aaa……
    Python练习题 012:字符统计
    Python练习题 011:成绩打分
  • 原文地址:https://www.cnblogs.com/doubest/p/13024118.html
Copyright © 2011-2022 走看看