1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| function maxSlidingWindow(nums: number[], k: number): number[] { const res: number[] = [], queue = new MonoQueue<number>() for (let i = 0; i < nums.length; i++) { queue.enqueue(nums[i]) if (i >= k) queue.dequeue(nums[i - k]) if (i >= k - 1) res.push(queue.top()) } return res }
class MonoQueue<T> { queue: T[] constructor() { this.queue = [] }
enqueue(value: T): void { while (this.queue.length && value > this.queue[this.queue.length - 1]) this.queue.pop() this.queue.push(value) }
dequeue(value: T): void { if (value === this.top()) this.queue.shift() }
top(): T { return this.queue[0] } }
|