有人会优化代码吗,不怎么会

P1886 滑动窗口 /【模板】单调队列

Scholar618 @ 2023-01-13 15:06:08

package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int n, k;
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        k = scanner.nextInt();
        int[] num = new int[n];
        Queue queue = new Queue(k, n);
//        System.out.println("n = " + n);
//        System.out.println("k = " + k);
        for (int i = 0; i < n; i++) {
            num[i] = scanner.nextInt();
//            System.out.print(arr[i]);
            queue.addQueue(num[i], k);
        }
        queue.show();
    }

    static class Queue {
        private int maxSize;//最大容量(3)
        private int front;//队列头
        private int rear;//队列尾
        private int[] arr;//存放队列的数组
        public int[] min_arr;
        public int[] max_arr;

        public Queue(int k, int n) {
            maxSize = k;
            arr = new int[n];
            min_arr = new int[n - k + 1];
            max_arr = new int[n - k + 1];
            front = 0;
            rear = 0;
        }

        public void addQueue(int n, int k){
            arr[rear++] = n;
            //判断队列是否满
//            System.out.println(rear);
//            System.out.println(arr[0]);
            if(rear - front == k ) {
//                System.out.println("front = " + front);
                Max(arr);
//                Min(arr);
                front++;
            }
        }

        public void Max(int[] arr){
            int max = arr[front];
            int min = arr[front];
            for (int i = front + 1; i < rear; i++) {
                if(max < arr[i]){
                    max = arr[i];
                }
                if(min > arr[i]){
                    min = arr[i];
                }
            }
            max_arr[front] = max;
            min_arr[front] = min;
        }

//        public void Min(int[] arr){
//            int min = arr[front];
//            for (int i = front + 1; i < rear; i++) {
//                if(min > arr[i]){
//                    min = arr[i];
//                }
//            }
//            min_arr[front] = min;
//        }

        public void show(){
            for (int i = 0; i < min_arr.length; i++) {
                System.out.print(min_arr[i] + " ");
            }
            System.out.println();
            for (int i = 0; i < max_arr.length; i++) {
                System.out.print(max_arr[i] + " ");
            }
        }

    }
}

by KKKZOZ @ 2023-01-13 15:24:43

package com.company;这句去掉再提交

能过6个点

你再把内存优化一下,能过的


|