今天主要是一些队列的应用
239 滑动窗口最大值
维护一个单调队列,确保队列中的数字是单调递减的。因为在队列中,只留下了每一次滑动窗口的最大值,所以尽管我们只记录了一部分窗口中的数字,可以确保总是记录了最大值。
class MonotonicQueue {
constructor() {
this.q = []
}
push(n) {
while (this.q.length !== 0 && this.q[this.q.length - 1] < n) {
this.q.pop()
}
this.q.push(n)
}
max() {
return this.q[0]
}
pop(n) {
if (this.q[0] === n) {
this.q.shift()
}
}
}
var maxSlidingWindow = function(nums, k) {
const window = new MonotonicQueue()
let res = []
for (let i = 0; i < nums.length; i++) {
if (i < k - 1) {
window.push(nums[i])
} else {
window.push(nums[i])
res.push(window.max())
window.pop(nums[i-k+1])
}
}
return res
};
347 前k个高频元素
对出现的次数排序,然后截取前k个元素。或者可以用priority queue
var topKFrequent = function(nums, k) {
const map = new Map();
for (let num of nums) {
map.set(num, map.has(num) ? (map.get(num) + 1): 1);
}
const list = Array.from(map).sort((a, b) => b[1] - a[1]);
return list.slice(0, k).map(n => n[0]);
};