Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9e1cc06

Browse files
committed
feat: add python and java solutions to lcof question
添加《剑指 Offer》题解:面试题59 - I. 滑动窗口的最大值
1 parent 29569dd commit 9e1cc06

File tree

3 files changed

+73
-2
lines changed

3 files changed

+73
-2
lines changed

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

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,20 +29,55 @@
2929

3030
## 解法
3131
<!-- 这里可写通用的实现逻辑 -->
32-
32+
双端队列实现。
3333

3434
### Python3
3535
<!-- 这里可写当前语言的特殊实现逻辑 -->
3636

3737
```python
38+
class Solution:
39+
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
40+
q, res = [], []
41+
for i, num in enumerate(nums):
42+
while len(q) != 0 and nums[q[-1]] <= num:
43+
q.pop(-1)
44+
q.append(i)
45+
46+
if q[0] == i - k:
47+
q = q[1:]
48+
if i >= k - 1:
49+
res.append(nums[q[0]])
50+
return res
3851

3952
```
4053

4154
### Java
4255
<!-- 这里可写当前语言的特殊实现逻辑 -->
4356

4457
```java
45-
58+
class Solution {
59+
public int[] maxSlidingWindow(int[] nums, int k) {
60+
int index = 0, n = nums.length;
61+
if (k == 0 || n == 0) {
62+
return new int[0];
63+
}
64+
int[] res = new int[n - k + 1];
65+
LinkedList<Integer> q = new LinkedList<>();
66+
for (int i = 0; i < n; ++i) {
67+
while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) {
68+
q.pollLast();
69+
}
70+
q.addLast(i);
71+
if (q.peekFirst() == i - k) {
72+
q.pollFirst();
73+
}
74+
if (i >= k - 1) {
75+
res[index++] = nums[q.peekFirst()];
76+
}
77+
}
78+
return res;
79+
}
80+
}
4681
```
4782

4883
### ...
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public int[] maxSlidingWindow(int[] nums, int k) {
3+
int index = 0, n = nums.length;
4+
if (k == 0 || n == 0) {
5+
return new int[0];
6+
}
7+
int[] res = new int[n - k + 1];
8+
LinkedList<Integer> q = new LinkedList<>();
9+
for (int i = 0; i < n; ++i) {
10+
while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) {
11+
q.pollLast();
12+
}
13+
q.addLast(i);
14+
if (q.peekFirst() == i - k) {
15+
q.pollFirst();
16+
}
17+
if (i >= k - 1) {
18+
res[index++] = nums[q.peekFirst()];
19+
}
20+
}
21+
return res;
22+
}
23+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution:
2+
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
3+
q, res = [], []
4+
for i, num in enumerate(nums):
5+
while len(q) != 0 and nums[q[-1]] <= num:
6+
q.pop(-1)
7+
q.append(i)
8+
9+
if q[0] == i - k:
10+
q = q[1:]
11+
if i >= k - 1:
12+
res.append(nums[q[0]])
13+
return res

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /