day 13 栈与队列(3/3)

39 阅读1分钟

239. 滑动窗口最大值

力扣题目链接

给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。

返回滑动窗口中的最大值。

解题思路:

维护一个队列,队列的长度为窗口的长度,且队首的元素是该滑动窗口的最大值。

实际上没有这样的一种数据结构,所以要我们手动定义一种这样的数据结构Mono Queue,在进行这个队列的出队和入队操作时,需要注意,我们需要且只需要这个窗口的最大值,所以在遇到比较小的数值的时候,可以直接跳过,维护该窗口的最大值即可。

var maxSlidingWindow = function (nums, k) {
    class MonoQueue {
        constructor() {
            this.queue = [];
        }
        enqueue(value) {
            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);
        }
        dequeue(value) {
            let front = this.front();
            if (front === value) {
                this.queue.shift();
            }
        }
        front() {
            return this.queue[0];
        }
    }
    let helperQueue = new MonoQueue();
    let i = 0, j = 0;
    let resArr = [];
    while (j < k) {
        helperQueue.enqueue(nums[j++]);
    }
    resArr.push(helperQueue.front());
    while (j < nums.length) {

        helperQueue.enqueue(nums[j]);
        helperQueue.dequeue(nums[i]);
        resArr.push(helperQueue.front());
        i++, j++;
    }
    return resArr;
};

347.前 K 个高频元素

力扣题目链接

给定一个非空的整数数组,返回其中出现频率前 k 高的元素。

示例 1:

  • 输入: nums = [1,1,1,2,2,3], k = 2
  • 输出: [1,2]

示例 2:

  • 输入: nums = [1], k = 1
  • 输出: [1]

解题思路:

方法1: 用JavaScript抖个机灵8

var topKFrequent = function(nums, k) {
    let countMap = new Map()
     for (let num of nums) {
        countMap.set(num, (countMap.get(num) || 0) + 1);
    }

   return [...countMap.entries()]
        .sort((a, b) => b[1] - a[1])
        .slice(0, k)
        .map(i => i[0]);
}

方法2: 维护堆 暂时略