mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
fix(0239): 新增一种java写法
This commit is contained in:
@ -208,6 +208,7 @@ public:
|
|||||||
|
|
||||||
Java:
|
Java:
|
||||||
```Java
|
```Java
|
||||||
|
//解法一
|
||||||
//自定义数组
|
//自定义数组
|
||||||
class MyQueue {
|
class MyQueue {
|
||||||
Deque<Integer> deque = new LinkedList<>();
|
Deque<Integer> deque = new LinkedList<>();
|
||||||
@ -260,6 +261,40 @@ class Solution {
|
|||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//解法二
|
||||||
|
//利用双端队列手动实现单调队列
|
||||||
|
/**
|
||||||
|
* 用一个单调队列来存储对应的下标,每当窗口滑动的时候,直接取队列的头部指针对应的值放入结果集即可
|
||||||
|
* 单调队列类似 (tail -->) 3 --> 2 --> 1 --> 0 (--> head) (右边为头结点,元素存的是下标)
|
||||||
|
*/
|
||||||
|
class Solution {
|
||||||
|
public int[] maxSlidingWindow(int[] nums, int k) {
|
||||||
|
ArrayDeque<Integer> deque = new ArrayDeque<>();
|
||||||
|
int n = nums.length;
|
||||||
|
int[] res = new int[n - k + 1];
|
||||||
|
int idx = 0;
|
||||||
|
for(int i = 0; i < n; i++) {
|
||||||
|
// 根据题意,i为nums下标,是要在[i - k + 1, k] 中选到最大值,只需要保证两点
|
||||||
|
// 1.队列头结点需要在[i - k + 1, k]范围内,不符合则要弹出
|
||||||
|
while(!deque.isEmpty() && deque.peek() < i - k + 1){
|
||||||
|
deque.poll();
|
||||||
|
}
|
||||||
|
// 2.既然是单调,就要保证每次放进去的数字要比末尾的都大,否则也弹出
|
||||||
|
while(!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
|
||||||
|
deque.pollLast();
|
||||||
|
}
|
||||||
|
|
||||||
|
deque.offer(i);
|
||||||
|
|
||||||
|
// 因为单调,当i增长到符合第一个k范围的时候,每滑动一步都将队列头节点放入结果就行了
|
||||||
|
if(i >= k - 1){
|
||||||
|
res[idx++] = nums[deque.peek()];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
Reference in New Issue
Block a user