力扣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;
    }
}
相关推荐
草莓熊Lotso40 分钟前
【数据结构初阶】--算法复杂度的深度解析
c语言·开发语言·数据结构·经验分享·笔记·其他·算法
KyollBM1 小时前
【CF】Day75——CF (Div. 2) B (数学 + 贪心) + CF 882 (Div. 2) C (01Trie | 区间最大异或和)
c语言·c++·算法
CV点灯大师1 小时前
C++算法训练营 Day10 栈与队列(1)
c++·redis·算法
GGBondlctrl1 小时前
【leetcode】递归,回溯思想 + 巧妙解法-解决“N皇后”,以及“解数独”题目
算法·leetcode·n皇后·有效的数独·解数独·映射思想·数学思想
武子康1 小时前
大数据-276 Spark MLib - 基础介绍 机器学习算法 Bagging和Boosting区别 GBDT梯度提升树
大数据·人工智能·算法·机器学习·语言模型·spark-ml·boosting
武子康2 小时前
大数据-277 Spark MLib - 基础介绍 机器学习算法 Gradient Boosting GBDT算法原理 高效实现
大数据·人工智能·算法·机器学习·ai·spark-ml·boosting
Andrew_Xzw2 小时前
数据结构与算法(快速基础C++版)
开发语言·数据结构·c++·python·深度学习·算法
超的小宝贝3 小时前
数据结构算法(C语言)
c语言·数据结构·算法
木子.李3479 小时前
排序算法总结(C++)
c++·算法·排序算法