代码随想录算法训练营第十三天 | 239. 滑动窗口最大值、347.前 K 个高频元素

文章介绍了如何使用队列和单调递减队列解决LeetCode的239题滑动窗口最大值问题,以及利用Map和自定义小顶堆解决347题前K个高频元素问题。解题过程中涉及数据结构和算法的应用,如队列的push和pop操作,以及小顶堆的构建和维护。
摘要由CSDN通过智能技术生成

LeetCode 239. 滑动窗口最大值

题目链接🔗:239. 滑动窗口最大值

解题思路🤔

整体思路是使用队列用来放入窗口内的元素,随着窗口移动,队列一进一出每次移动后队列计算出最大值。

这样就需要定义一个队列,一个push方法用于压入窗口内的元素,一个pop方法用于弹出窗口内的元素,一个front方法用于返回需要的最大值。

需要解决的问题是保持队列是一个单调递减队列,把队列中最大的元素放到最左边,用front方法返回即可。此时遇到问题,那就是如何保证在维持单调队列时移动滑动窗口。

解决方法:

pop方法:如果窗口移除的元素等于单调队列的出口元素,那么队列弹出元素,否则不用任何操作

push方法:如果push的元素大于入口元素的数值,那么就将队列入口的元素弹出,直到push元素的数值小于等于队列入口元素的数值为止

遇到的问题😢

代码实现👨🏻‍💻

使用队列

var maxSlidingWindow = function (nums, k) { // 滑动窗口大小为k
    class MyQueue {
        queue;
        constructor() { // 构造函数,初始化队列
            this.queue = [];
        }

        pushQueue(value) { // 如果push的数值大于入口元素的数值,那么就将队列后端的数值弹出,直到push的数值小于等于队列入口元素的数值为止。
            let back = this.queue[this.queue.length - 1];
            while (back !== undefined && back < value) {
                this.queue.pop();
                back = this.queue[this.queue.length - 1];
            }
            this.queue.push(value);
        }

        popQueue(value) { // 每次弹出的时候,比较当前要弹出的数值是否等于队列出口元素的数值,如果相等则弹出
            let front = this.front();
            if (front === value) this.queue.shift();
        }

        front() { // 查询当前队列里的最大值 直接返回队列前端也就是front
            return this.queue[0];
        }
    }

    let que = new MyQueue();
    let i = 0, j = 0;
    let res = [];

    while (j < k) que.pushQueue(nums[j++]); // 将前k的元素放入队列

    res.push(que.front()); // res记录前k的元素的最大值

    while (j < nums.length) {
        que.pushQueue(nums[j]); // 滑动窗口前加入最后面的元素
        que.popQueue(nums[i]);  // 滑动窗口移除最前面元素
        res.push(que.front());  // 记录对应的最大值
        i++, j++;
    }
    
    return res;
};

总结📖


LeetCode 347.前 K 个高频元素

题目链接🔗:347.前 K 个高频元素

解题思路🤔

  1. 统计元素出现频率 => 使用map
  2. 对频率排序 => 大小为k的小顶堆,每次移动更新时将最小的元素弹出
  3. 找出前k个高频元素 => 小顶堆最后留下的就是最大前k个元素

遇到的问题😢

自己构造堆太麻烦了…等学完二叉树回来复习

代码实现👨🏻‍💻

第一种方法

// js 没有堆 需要自己构造
class Heap {
    constructor(compareFn) {
        this.compareFn = compareFn;
        this.queue = [];
    }

    // 添加
    push(item) {
        // 推入元素
        this.queue.push(item);

        // 上浮
        let index = this.size() - 1; // 记录推入元素下标
        let parent = Math.floor((index - 1) / 2); // 记录父节点下标

        while (parent >= 0 && this.compare(parent, index) > 0) { // 注意compare参数顺序
            [this.queue[index], this.queue[parent]] = [this.queue[parent], this.queue[index]];

            // 更新下标
            index = parent;
            parent = Math.floor((index - 1) / 2);
        }
    }

    // 获取堆顶元素并移除
    pop() {
        // 堆顶元素
        const out = this.queue[0];

        // 移除堆顶元素 填入最后一个元素
        this.queue[0] = this.queue.pop();

        // 下沉
        let index = 0; // 记录下沉元素下标
        let left = 1; // left 是左子节点下标 left + 1 则是右子节点下标
        let searchChild = this.compare(left, left + 1) > 0 ? left + 1 : left;

        while (searchChild !== undefined && this.compare(index, searchChild) > 0) { // 注意compare参数顺序
            [this.queue[index], this.queue[searchChild]] = [this.queue[searchChild], this.queue[index]];

            // 更新下标
            index = searchChild;
            left = 2 * index + 1;
            searchChild = this.compare(left, left + 1) > 0 ? left + 1 : left;
        }

        return out;
    }

    size() {
        return this.queue.length;
    }

    // 使用传入的 compareFn 比较两个位置的元素
    compare(index1, index2) {
        // 处理下标越界问题
        if (this.queue[index1] === undefined) return 1;
        if (this.queue[index2] === undefined) return -1;

        return this.compareFn(this.queue[index1], this.queue[index2]);
    }

}

const topKFrequent = function (nums, k) {
    const map = new Map();

    for (const num of nums) {
        map.set(num, (map.get(num) || 0) + 1);
    }

    // 创建小顶堆
    const heap= new Heap((a, b) => a[1] - b[1]);

    // entry 是一个长度为2的数组,0位置存储key,1位置存储value
    for (const entry of map.entries()) {
        heap.push(entry);

        if (heap.size() > k) {
            heap.pop();
        }
    }

    // return heap.queue.map(e => e[0]);

    const res = [];

    for (let i = heap.size() - 1; i >= 0; i--) {
        res[i] = heap.pop()[0];
    }

    return res;
};

总结📖


今日收获

  1. 中等难度的题目果然就比较棘手
  2. 对队列、栈的理解还不足,需要加强
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值