forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0239-sliding-window-maximum.js
82 lines (77 loc) · 2 KB
/
0239-sliding-window-maximum.js
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
function Node(value) {
this.value = value;
this.prev = null;
this.next = null;
}
function Deque() {
this.left = null;
this.right = null;
this.size = 0;
this.pushRight = function (value) {
const node = new Node(value);
if (this.size == 0) {
this.left = node;
this.right = node;
} else {
this.right.next = node;
node.prev = this.right;
this.right = node;
}
this.size++;
return this.size;
};
this.popRight = function () {
if (this.size == 0) return null;
const removedNode = this.right;
this.right = this.right.prev;
if (this.right) this.right.next = null;
this.size--;
return removedNode;
};
this.pushLeft = function (value) {
const node = new Node(value);
if (this.size == 0) {
this.left = node;
this.right = node;
} else {
this.left.prev = node;
node.next = this.left;
this.left = node;
}
this.size++;
return this.size;
};
this.popLeft = function () {
if (this.size == 0) return null;
const removedNode = this.left;
this.left = this.left.next;
if (this.left) this.left.prev = null;
this.size--;
return removedNode;
};
}
var maxSlidingWindow = function (nums, k) {
const output = [];
let deque = new Deque();
let left = 0;
let right = 0;
while (right < nums.length) {
// pop smaller values from q
while (deque.right && nums[deque.right.value] < nums[right])
deque.popRight();
deque.pushRight(right);
// remove left val from window
if (left > deque.left.value) deque.popLeft();
if (right + 1 >= k) {
output.push(nums[deque.left.value]);
left++;
}
right++;
}
return output;
};