File tree 1 file changed +57
-0
lines changed
1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change @@ -80,3 +80,60 @@ var maxSlidingWindow = function (nums, k) {
80
80
}
81
81
return output ;
82
82
} ;
83
+
84
+ /**
85
+ * @param {number[] } nums
86
+ * @param {number } k
87
+ * @return {number[] }
88
+ */
89
+
90
+ // Deque Implementation using Lazy Deletion
91
+ class LazyDeletionDeque {
92
+ constructor ( ) {
93
+ this . deque = [ ] ;
94
+ this . leftIdx = 0 ;
95
+ }
96
+
97
+ isEmpty = ( ) => {
98
+ return this . deque . length === this . leftIdx ;
99
+ } ;
100
+ push = ( num ) => {
101
+ this . deque . push ( num ) ;
102
+ } ;
103
+ popFront = ( ) => {
104
+ this . leftIdx ++ ;
105
+ } ;
106
+ popBack = ( ) => {
107
+ ! this . isEmpty ( ) && this . deque . pop ( ) ;
108
+ } ;
109
+ front = ( ) => {
110
+ return this . deque [ this . leftIdx ] ;
111
+ } ;
112
+ back = ( ) => {
113
+ return this . deque [ this . deque . length - 1 ] ;
114
+ } ;
115
+ }
116
+
117
+ var maxSlidingWindowWithLazyDeletionDeque = function ( nums , k ) {
118
+ const deque = new LazyDeletionDeque ( ) ;
119
+ const answer = [ ] ;
120
+ let leftWindow = 0 ;
121
+ for ( let rightWindow = 0 ; rightWindow < nums . length ; rightWindow ++ ) {
122
+ const rightNum = nums [ rightWindow ] ;
123
+ while ( ! deque . isEmpty ( ) && rightNum > deque . back ( ) ) {
124
+ deque . popBack ( ) ;
125
+ }
126
+ deque . push ( rightNum ) ;
127
+
128
+ if ( rightWindow >= k - 1 ) {
129
+ const dequeFront = deque . front ( ) ;
130
+ const leftNum = nums [ leftWindow ] ;
131
+ if ( leftNum === dequeFront ) {
132
+ deque . popFront ( ) ;
133
+ }
134
+ answer . push ( dequeFront ) ;
135
+ leftWindow ++ ;
136
+ }
137
+ }
138
+ return answer ;
139
+ } ;
You can’t perform that action at this time.
0 commit comments