33
33
34
34
<!-- 这里可写通用的实现逻辑 -->
35
35
36
- 单调队列。
36
+ ** 方法一: 单调队列**
37
37
38
38
单调队列常见模型:找出滑动窗口中的最大值/最小值。模板:
39
39
@@ -48,6 +48,8 @@ for i in range(n):
48
48
q.append(i)
49
49
```
50
50
51
+ 时间复杂度 $O(n)$,空间复杂度 $O(k)$。其中 $n$ 为数组长度。
52
+
51
53
<!-- tabs:start -->
52
54
53
55
### ** Python3**
@@ -57,17 +59,17 @@ for i in range(n):
57
59
``` python
58
60
class Solution :
59
61
def maxSlidingWindow (self , nums : List[int ], k : int ) -> List[int ]:
60
- q, res = deque(), []
61
- for i, num in enumerate (nums):
62
- if q and i - k + 1 > q[0 ]:
62
+ q = deque()
63
+ ans = []
64
+ for i, x in enumerate (nums):
65
+ if q and i - q[0 ] + 1 > k:
63
66
q.popleft()
64
- while q and nums[q[- 1 ]] <= num :
67
+ while q and nums[q[- 1 ]] <= x :
65
68
q.pop()
66
69
q.append(i)
67
70
if i >= k - 1 :
68
- res.append(nums[q[0 ]])
69
- return res
70
-
71
+ ans.append(nums[q[0 ]])
72
+ return ans
71
73
```
72
74
73
75
### ** Java**
@@ -77,82 +79,45 @@ class Solution:
77
79
``` java
78
80
class Solution {
79
81
public int [] maxSlidingWindow (int [] nums , int k ) {
80
- int index = 0 , n = nums. length;
81
- if (k == 0 || n == 0 ) {
82
- return new int [0 ];
83
- }
84
- int [] res = new int [n - k + 1 ];
85
- LinkedList<Integer > q = new LinkedList<> ();
82
+ int n = nums. length;
83
+ int [] ans = new int [n - k + 1 ];
84
+ Deque<Integer > q = new ArrayDeque<> ();
86
85
for (int i = 0 ; i < n; ++ i) {
86
+ if (! q. isEmpty() && i - q. peek() + 1 > k) {
87
+ q. poll();
88
+ }
87
89
while (! q. isEmpty() && nums[q. peekLast()] <= nums[i]) {
88
90
q. pollLast();
89
91
}
90
- q. addLast(i);
91
- if (q. peekFirst() == i - k) {
92
- q. pollFirst();
93
- }
92
+ q. offer(i);
94
93
if (i >= k - 1 ) {
95
- res[index ++ ] = nums[q. peekFirst ()];
94
+ ans[i - k + 1 ] = nums[q. peek ()];
96
95
}
97
96
}
98
- return res ;
97
+ return ans ;
99
98
}
100
99
}
101
100
```
102
101
103
- ### ** JavaScript**
104
-
105
- ``` js
106
- /**
107
- * @param {number[]} nums
108
- * @param {number} k
109
- * @return {number[]}
110
- */
111
- var maxSlidingWindow = function (nums , k ) {
112
- if (! nums .length || ! k) return [];
113
- if (k === 1 ) return nums;
114
- let res = [];
115
- let tmpMax = - Infinity ;
116
- let len = nums .length ;
117
- let window = [];
118
- for (let i = 0 ; i < k; i++ ) {
119
- tmpMax = Math .max (nums[i], tmpMax);
120
- window .push (nums[i]);
121
- }
122
- res .push (tmpMax);
123
- for (let i = k; i < len; i++ ) {
124
- let a = window .shift ();
125
- window .push (nums[i]);
126
- if (nums[i] > tmpMax) {
127
- tmpMax = nums[i];
128
- } else if (tmpMax === a) {
129
- tmpMax = Math .max (... window );
130
- }
131
- res .push (tmpMax);
132
- }
133
- return res;
134
- };
135
- ```
136
-
137
102
### ** C++**
138
103
139
104
``` cpp
140
105
class Solution {
141
106
public:
142
107
vector<int > maxSlidingWindow(vector<int >& nums, int k) {
143
108
vector<int > ans;
144
- deque<int > window ;
109
+ deque<int > q ;
145
110
int n = nums.size();
146
111
for (int i = 0; i < n; ++i) {
147
- while (!window .empty() && nums [ window.back() ] <= nums [ i ] ) {
148
- window.pop_back ();
112
+ if (!q .empty() && i - q.front() + 1 > k ) {
113
+ q.pop_front ();
149
114
}
150
- window.push_back(i);
151
- if (window.front() == i - k) {
152
- window.pop_front();
115
+ while (!q.empty() && nums[ q.back()] <= nums[ i] ) {
116
+ q.pop_back();
153
117
}
118
+ q.push_back(i);
154
119
if (i >= k - 1) {
155
- ans.push_back(nums[ window .front()] );
120
+ ans.push_back(nums[ q .front()] );
156
121
}
157
122
}
158
123
return ans;
@@ -163,53 +128,72 @@ public:
163
128
### **Go**
164
129
165
130
```go
166
- func maxSlidingWindow(nums []int, k int) []int {
167
- ans := make([]int, 0, len(nums)-k+1)
168
- window := make([]int, 0)
169
- for i, num := range nums {
170
- for len(window) != 0 && nums[window[len(window)-1]] <= num {
171
- window = window[:len(window)-1]
131
+ func maxSlidingWindow(nums []int, k int) (ans []int) {
132
+ q := []int{}
133
+ for i, x := range nums {
134
+ for len(q) > 0 && i-q[0]+1 > k {
135
+ q = q[1:]
172
136
}
173
- window = append(window, i)
174
- if window[0] == i-k {
175
- window = window[1:]
137
+ for len(q) > 0 && nums[q[len(q)-1]] <= x {
138
+ q = q[:len(q)-1]
176
139
}
140
+ q = append(q, i)
177
141
if i >= k-1 {
178
- ans = append(ans, nums[window [0]])
142
+ ans = append(ans, nums[q [0]])
179
143
}
180
144
}
181
- return ans
145
+ return
182
146
}
183
147
```
184
148
149
+ ### ** JavaScript**
150
+
151
+ ``` js
152
+ /**
153
+ * @param {number[]} nums
154
+ * @param {number} k
155
+ * @return {number[]}
156
+ */
157
+ var maxSlidingWindow = function (nums , k ) {
158
+ const q = [];
159
+ const n = nums .length ;
160
+ const ans = [];
161
+ for (let i = 0 ; i < n; ++ i) {
162
+ while (q .length && i - q[0 ] + 1 > k) {
163
+ q .shift ();
164
+ }
165
+ while (q .length && nums[q[q .length - 1 ]] <= nums[i]) {
166
+ q .pop ();
167
+ }
168
+ q .push (i);
169
+ if (i >= k - 1 ) {
170
+ ans .push (nums[q[0 ]]);
171
+ }
172
+ }
173
+ return ans;
174
+ };
175
+ ```
176
+
185
177
### ** TypeScript**
186
178
187
179
``` ts
188
180
function maxSlidingWindow(nums : number [], k : number ): number [] {
181
+ const q: number [] = [];
189
182
const n = nums .length ;
190
- const res = [];
191
- if (n === 0 || k === 0 ) {
192
- return res ;
193
- }
194
- const queue = [];
195
- for (let i = 0 ; i < k ; i ++ ) {
196
- while (queue .length !== 0 && queue [queue .length - 1 ] < nums [i ]) {
197
- queue .pop ();
183
+ const ans: number [] = [];
184
+ for (let i = 0 ; i < n ; ++ i ) {
185
+ while (q .length && i - q [0 ] + 1 > k ) {
186
+ q .shift ();
198
187
}
199
- queue .push (nums [i ]);
200
- }
201
- res .push (queue [0 ]);
202
- for (let i = k ; i < n ; i ++ ) {
203
- if (queue [0 ] === nums [i - k ]) {
204
- queue .shift ();
188
+ while (q .length && nums [q [q .length - 1 ]] <= nums [i ]) {
189
+ q .pop ();
205
190
}
206
- while (queue .length !== 0 && queue [queue .length - 1 ] < nums [i ]) {
207
- queue .pop ();
191
+ q .push (i );
192
+ if (i >= k - 1 ) {
193
+ ans .push (nums [q [0 ]]);
208
194
}
209
- queue .push (nums [i ]);
210
- res .push (queue [0 ]);
211
195
}
212
- return res ;
196
+ return ans ;
213
197
}
214
198
```
215
199
@@ -221,29 +205,21 @@ impl Solution {
221
205
pub fn max_sliding_window (nums : Vec <i32 >, k : i32 ) -> Vec <i32 > {
222
206
let k = k as usize ;
223
207
let n = nums . len ();
224
- if n == 0 || k == 0 {
225
- return Vec :: new ();
226
- }
227
- let mut res = vec! [0 ; n - k + 1 ];
228
- let mut queue = VecDeque :: new ();
229
- for i in 0 .. k {
230
- while ! queue . is_empty () && * queue . back (). unwrap () < nums [i ] {
231
- queue . pop_back ();
208
+ let mut ans = vec! [0 ; n - k + 1 ];
209
+ let mut q = VecDeque :: new ();
210
+ for i in 0 .. n {
211
+ while ! q . is_empty () && i - q [0 ] + 1 > k {
212
+ q . pop_front ();
232
213
}
233
- queue . push_back (nums [i ]);
234
- }
235
- res [0 ] = queue [0 ];
236
- for i in k .. n {
237
- if nums [i - k ] == queue [0 ] {
238
- queue . pop_front ();
214
+ while ! q . is_empty () && nums [* q . back (). unwrap ()] <= nums [i ] {
215
+ q . pop_back ();
239
216
}
240
- while ! queue . is_empty () && * queue . back (). unwrap () < nums [i ] {
241
- queue . pop_back ();
217
+ q . push_back (i );
218
+ if i >= k - 1 {
219
+ ans [i - k + 1 ] = nums [q [0 ]]
242
220
}
243
- queue . push_back (nums [i ]);
244
- res [i - k + 1 ] = queue [0 ];
245
221
}
246
- res
222
+ ans
247
223
}
248
224
}
249
225
```
0 commit comments