Skip to content

Commit cb5b1db

Browse files
authored
Update 239-sliding-window-maximum.js
1 parent 5119e34 commit cb5b1db

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

239-sliding-window-maximum.js

+67
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,70 @@ const maxSlidingWindow = function(nums, k) {
2323

2424
return res
2525
};
26+
27+
// another
28+
29+
/**
30+
* @param {number[]} nums
31+
* @param {number} k
32+
* @return {number[]}
33+
*/
34+
var maxSlidingWindow = function (nums, k) {
35+
if (k === 0) return []
36+
const deque = new Deque()
37+
for (let i = 0; i < k - 1; i++) {
38+
while (!deque.isEmpty() && deque.last().val <= nums[i]) deque.pop()
39+
deque.enqueue({ val: nums[i], idx: i })
40+
}
41+
const result = []
42+
for (let i = k - 1; i < nums.length; i++) {
43+
if (!deque.isEmpty() && deque.first().idx <= i - k) deque.dequeue()
44+
while (!deque.isEmpty() && deque.last().val <= nums[i]) deque.pop()
45+
deque.enqueue({ val: nums[i], idx: i })
46+
result.push(deque.first().val)
47+
}
48+
return result
49+
}
50+
51+
class Deque {
52+
constructor() {
53+
this.head = new Node()
54+
this.tail = this.head
55+
}
56+
57+
isEmpty() {
58+
return this.head.next === null
59+
}
60+
61+
first() {
62+
return this.head.next.value
63+
}
64+
65+
last() {
66+
return this.tail.value
67+
}
68+
69+
dequeue() {
70+
this.head = this.head.next
71+
this.head.prev = null
72+
}
73+
74+
enqueue(value) {
75+
this.tail.next = new Node(value)
76+
this.tail.next.prev = this.tail
77+
this.tail = this.tail.next
78+
}
79+
80+
pop() {
81+
this.tail = this.tail.prev
82+
this.tail.next = null
83+
}
84+
}
85+
86+
class Node {
87+
constructor(value) {
88+
this.value = value
89+
this.next = null
90+
this.prev = null
91+
}
92+
}

0 commit comments

Comments
 (0)