1 Star 0 Fork 0

Neo_1001/LeetCode刷题记录

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
lc_239v2.java 1.27 KB
一键复制 编辑 原始数据 按行查看 历史
Neo_1001 提交于 2024-04-10 22:16 . first commit
package LeetCode;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
public class lc_239v2 {
public static class myQueue {
LinkedList<Integer> queue = new LinkedList<>();
public void add(int val) {
while (!queue.isEmpty() && val > queue.getLast()) queue.removeLast();
queue.add(val);
}
public void pop(int val) {
if (!queue.isEmpty() && val == queue.getFirst()) queue.removeFirst();
}
public int peek() {
return queue.getFirst();
}
}
public static int[] maxSlidingWindow(int[] nums, int k) {
if (nums.length <= k) return nums;
int[] res = new int[nums.length - k + 1];
myQueue que = new myQueue();
for (int i = 0; i < k; i++) {
que.add(nums[i]);
}
int idx = 0;
res[idx++] = que.peek();
for (int i = k; i < nums.length; i++) {
que.add(nums[i]);
que.pop(nums[i - k]);
res[idx++] = que.peek();
}
return res;
}
public static void main(String[] args) {
int[] nums = new int[]{1, 3, -1, -3, 5, 3, 6, 7};
System.out.println(Arrays.toString(maxSlidingWindow(nums,3)));
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/neo1001/leet-code-practice-record.git
git@gitee.com:neo1001/leet-code-practice-record.git
neo1001
leet-code-practice-record
LeetCode刷题记录
master

搜索帮助