Open Ni-Guvara opened 1 year ago
class MyQueen{
LinkedList<Integer> quee = new LinkedList<>();
void push(int n){
while(!quee.isEmpty() && quee.getLast() < n){
quee.pollLast();
}
quee.addLast(n);
}
int max(){
return quee.getFirst();
}
void pop(int n){
if (n == quee.getFirst()){
quee.pollFirst();
}
}
}
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int len = nums.length;
MyQueen myQueen = new MyQueen();
List<Integer> res = new ArrayList<>();
for (int i = 0; i < len; i++) {
if (i < k - 1){
myQueen.push(nums[i]);
}else {
// 窗口前移, 加入新数字
myQueen.push(nums[i]);
// 记录当前窗口的最大值
res.add(myQueen.max());
// 移除旧数字
myQueen.pop(nums[i - k + 1]);
}
}
int[] ret = new int[res.size()];
for (int i = 0; i < ret.length; i++){
ret[i] = res.get(i);
}
return ret;
}
}