力扣239. 滑动窗口最大值

Problem: 239. 滑动窗口最大值

文章目录

题目描述

思路

1.编写实现优先队列类:

1.1.实现push(int n) :将元素n添加到队列尾,同时将n前面大于n的元素删除

1.2.实现int max() :将队列头元素取出(由于实现了push所以此时队列头元素为当前队列中的最大值)

1.3.实现pop(int n):将队列头的元素n删除(代码实现中,需要先检查n是否还在当前对头。因为n有可能已经删除掉了)
2.题目代码逻辑实现:
2.1.生成窗口:将前k个元素添加到实现的优先队列中;

2.2.维护窗口:每次push一个新的元素到窗口,再取出当前窗口中的最大值添加到结果集合中,再删除之前的窗口左侧

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为数组nums的长度

空间复杂度:

O ( n ) O(n) O(n);

Code

java 复制代码
/* Monotonic queue implementation */
class MonotonicQueue {
    LinkedList<Integer> maxq = new LinkedList<>();

    public void push(int n) {
        // Delete all elements smaller than n
        while (!maxq.isEmpty() && maxq.getLast() < n) {
            maxq.pollLast();
        }
        // Then add n to the tail
        maxq.addLast(n);
    }

    public int max() {
        return maxq.getFirst();
    }

    public void pop(int n) {
        if (n == maxq.getFirst()) {
            maxq.pollFirst();
        }
    }
}

class Solution {
    /***
     * Sliding Window Maximum
     *
     * @param nums Given array
     * @param k Given number
     * @return int[]
     */
    public int[] maxSlidingWindow(int[] nums, int k) {
        MonotonicQueue window = new MonotonicQueue();
        List<Integer> res = new ArrayList<>();

        for (int i = 0; i < nums.length; i++) {
            if (i < k - 1) {
                // Fill the front k-1 of the window first
                window.push(nums[i]);
            } else {
                // The window slides forward to add a new number
                window.push(nums[i]);
                // Record the maximum value of the current window
                res.add(window.max());
                // Remove old numbers
                window.pop(nums[i - k + 1]);
            }
        }
        // Needs to be converted to an int[] array and returned
        int[] arr = new int[res.size()];
        for (int i = 0; i < res.size(); i++) {
            arr[i] = res.get(i);
        }
        return arr;
    }
}
相关推荐
bIo7lyA8v1 分钟前
算法性能建模的数值方法与误差分析的技术8
算法
Smilecoc2 分钟前
决策树(四):决策树实战之鸢尾花分类
算法·决策树·分类
-Thinker2 分钟前
【无标题】
java·开发语言·算法·图搜索
数据仓库搬砖人2 分钟前
DBSCAN 原理深度解析:从聚类算法到风控团伙识别的实战指南
算法
凡人叶枫10 分钟前
Effective C++ 条款24:若所有参数皆须要类型转换,请为此采用 non-member 函数
linux·前端·c++·算法·嵌入式开发
洛水水12 分钟前
【力扣100题】87.只出现一次的数字
数据结构·算法·leetcode
HZ·湘怡12 分钟前
排序算法之希尔排序(2)--菜鸟先飞
数据结构·算法·排序算法·希尔排序
乐观勇敢坚强的老彭14 分钟前
2026全国青少年信息素养大赛(Python小学组)复赛复习讲义
python·算法·数学建模
林间码客23 分钟前
02数据挖掘:数据属性、类型与相似性度量
人工智能·算法·机器学习
阿标在干嘛24 分钟前
从“拍脑袋”到“数据驱动”:政策平台的A/B测试实践
大数据·人工智能·算法·ab测试