Skip to content

Commit cce241b

Browse files
committed
feat: add solutions to lcof problem: No.59.1
1 parent a6a98bb commit cce241b

File tree

8 files changed

+157
-206
lines changed

8 files changed

+157
-206
lines changed

lcof/面试题59 - I. 滑动窗口的最大值/README.md

Lines changed: 86 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333

3434
<!-- 这里可写通用的实现逻辑 -->
3535

36-
单调队列
36+
**方法一:单调队列**
3737

3838
单调队列常见模型:找出滑动窗口中的最大值/最小值。模板:
3939

@@ -48,6 +48,8 @@ for i in range(n):
4848
q.append(i)
4949
```
5050

51+
时间复杂度 $O(n)$,空间复杂度 $O(k)$。其中 $n$ 为数组长度。
52+
5153
<!-- tabs:start -->
5254

5355
### **Python3**
@@ -57,17 +59,17 @@ for i in range(n):
5759
```python
5860
class Solution:
5961
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:
6366
q.popleft()
64-
while q and nums[q[-1]] <= num:
67+
while q and nums[q[-1]] <= x:
6568
q.pop()
6669
q.append(i)
6770
if i >= k - 1:
68-
res.append(nums[q[0]])
69-
return res
70-
71+
ans.append(nums[q[0]])
72+
return ans
7173
```
7274

7375
### **Java**
@@ -77,82 +79,45 @@ class Solution:
7779
```java
7880
class Solution {
7981
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<>();
8685
for (int i = 0; i < n; ++i) {
86+
if (!q.isEmpty() && i - q.peek() + 1 > k) {
87+
q.poll();
88+
}
8789
while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) {
8890
q.pollLast();
8991
}
90-
q.addLast(i);
91-
if (q.peekFirst() == i - k) {
92-
q.pollFirst();
93-
}
92+
q.offer(i);
9493
if (i >= k - 1) {
95-
res[index++] = nums[q.peekFirst()];
94+
ans[i - k + 1] = nums[q.peek()];
9695
}
9796
}
98-
return res;
97+
return ans;
9998
}
10099
}
101100
```
102101

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-
137102
### **C++**
138103

139104
```cpp
140105
class Solution {
141106
public:
142107
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
143108
vector<int> ans;
144-
deque<int> window;
109+
deque<int> q;
145110
int n = nums.size();
146111
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();
149114
}
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();
153117
}
118+
q.push_back(i);
154119
if (i >= k - 1) {
155-
ans.push_back(nums[window.front()]);
120+
ans.push_back(nums[q.front()]);
156121
}
157122
}
158123
return ans;
@@ -163,53 +128,72 @@ public:
163128
### **Go**
164129
165130
```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:]
172136
}
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]
176139
}
140+
q = append(q, i)
177141
if i >= k-1 {
178-
ans = append(ans, nums[window[0]])
142+
ans = append(ans, nums[q[0]])
179143
}
180144
}
181-
return ans
145+
return
182146
}
183147
```
184148

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+
185177
### **TypeScript**
186178

187179
```ts
188180
function maxSlidingWindow(nums: number[], k: number): number[] {
181+
const q: number[] = [];
189182
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();
198187
}
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();
205190
}
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]]);
208194
}
209-
queue.push(nums[i]);
210-
res.push(queue[0]);
211195
}
212-
return res;
196+
return ans;
213197
}
214198
```
215199

@@ -221,29 +205,21 @@ impl Solution {
221205
pub fn max_sliding_window(nums: Vec<i32>, k: i32) -> Vec<i32> {
222206
let k = k as usize;
223207
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();
232213
}
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();
239216
}
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]]
242220
}
243-
queue.push_back(nums[i]);
244-
res[i - k + 1] = queue[0];
245221
}
246-
res
222+
ans
247223
}
248224
}
249225
```

lcof/面试题59 - I. 滑动窗口的最大值/Solution.cpp

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,20 @@ class Solution {
22
public:
33
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
44
vector<int> ans;
5-
deque<int> window;
5+
deque<int> q;
66
int n = nums.size();
77
for (int i = 0; i < n; ++i) {
8-
while (!window.empty() && nums[window.back()] <= nums[i]) {
9-
window.pop_back();
8+
if (!q.empty() && i - q.front() + 1 > k) {
9+
q.pop_front();
1010
}
11-
window.push_back(i);
12-
if (window.front() == i - k) {
13-
window.pop_front();
11+
while (!q.empty() && nums[q.back()] <= nums[i]) {
12+
q.pop_back();
1413
}
14+
q.push_back(i);
1515
if (i >= k - 1) {
16-
ans.push_back(nums[window.front()]);
16+
ans.push_back(nums[q.front()]);
1717
}
1818
}
1919
return ans;
2020
}
21-
};
21+
};
Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
1-
func maxSlidingWindow(nums []int, k int) []int {
2-
ans := make([]int, 0, len(nums)-k+1)
3-
window := make([]int, 0)
4-
for i, num := range nums {
5-
for len(window) != 0 && nums[window[len(window)-1]] <= num {
6-
window = window[:len(window)-1]
1+
func maxSlidingWindow(nums []int, k int) (ans []int) {
2+
q := []int{}
3+
for i, x := range nums {
4+
for len(q) > 0 && i-q[0]+1 > k {
5+
q = q[1:]
76
}
8-
window = append(window, i)
9-
if window[0] == i-k {
10-
window = window[1:]
7+
for len(q) > 0 && nums[q[len(q)-1]] <= x {
8+
q = q[:len(q)-1]
119
}
10+
q = append(q, i)
1211
if i >= k-1 {
13-
ans = append(ans, nums[window[0]])
12+
ans = append(ans, nums[q[0]])
1413
}
1514
}
16-
return ans
17-
}
15+
return
16+
}
Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,20 @@
11
class Solution {
22
public int[] maxSlidingWindow(int[] nums, int k) {
33
int n = nums.length;
4-
if (n == 0) {
5-
return new int[0];
6-
}
7-
int[] res = new int[n - k + 1];
8-
Deque<Integer> q = new LinkedList<>();
9-
for (int i = 0, j = 0; i < n; ++i) {
10-
if (!q.isEmpty() && i - k + 1 > q.peekFirst()) {
11-
q.pollFirst();
4+
int[] ans = new int[n - k + 1];
5+
Deque<Integer> q = new ArrayDeque<>();
6+
for (int i = 0; i < n; ++i) {
7+
if (!q.isEmpty() && i - q.peek() + 1 > k) {
8+
q.poll();
129
}
1310
while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) {
1411
q.pollLast();
1512
}
16-
q.offerLast(i);
13+
q.offer(i);
1714
if (i >= k - 1) {
18-
res[j++] = nums[q.peekFirst()];
15+
ans[i - k + 1] = nums[q.peek()];
1916
}
2017
}
21-
return res;
18+
return ans;
2219
}
2320
}

0 commit comments

Comments
 (0)