当前位置:网站首页>剑指 Offer 59 - I. 滑动窗口的最大值
剑指 Offer 59 - I. 滑动窗口的最大值
2022-06-29 19:37:00 【Yake1965】
剑指 Offer 59 - I. 滑动窗口的最大值
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int n = nums.length;
if(n == 0) return new int[0];
int[] ans = new int[n - k + 1];
PriorityQueue<int[]> q = new PriorityQueue<>((a, b) -> b[0] - a[0]);
for(int i = 0; i < k; i++){
q.offer(new int[]{
nums[i], i});
}
ans[0] = q.peek()[0];
for(int i = k; i < n; i++){
q.offer(new int[]{
nums[i], i});
while(q.peek()[1] <= i - k) q.poll();
ans[i-k+1] = q.peek()[0];
}
return ans;
}
}
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int n = nums.length;
if(n == 0) return new int[0];
PriorityQueue<Integer> q = new PriorityQueue<>((i, j) -> nums[j] - nums[i]);
int[] ans = new int[n - k + 1];
for(int i = 0; i < k; i++){
q.offer(i);
}
ans[0] = nums[q.peek()];
for(int i = k; i < n; i++){
q.offer(i);
while(q.peek() <= i - k){
q.poll();
}
ans[i-k+1] = nums[q.peek()];
}
return ans;
}
}
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int n = nums.length;
if(n == 0) return new int[0];
int[] res = new int[n - k + 1];
Deque<Integer> q = new LinkedList<>();
for(int i = 0; i < n; i++){
// 单调队列
while (!q.isEmpty() && nums[i] >= nums[q.peekLast()]) {
q.pollLast();
}
q.add(i); // 索引
int left = i - k + 1; // 当 left >= 0 时开始滑动窗口
if (q.peek() < left) q.poll();
if (left >= 0) res[left] = nums[q.peek()];
}
return res;
}
}
边栏推荐
- 1404万!四川省人社厅关系型数据库及中间件软件系统升级采购招标!
- @SneakyThrows注解
- 全局变量和静态变量的初始化
- go: 如何编写一个正确的udp服务端
- AI scene Storage Optimization: yunzhisheng supercomputing platform storage practice based on juicefs
- 小米笔试真题一
- 出逃与进军,临期食品的「双面江湖」
- PHP Laravel 使用 aws 负载均衡器的 ip 错误问题
- What if the win11 policy service is disabled? Solution to disabling win11 policy service
- Rejected by a large company? Tencent experts summarized 11 reasons for being rejected!
猜你喜欢

Win11策略服务被禁用怎么办?Win11策略服务被禁用的解决方法

shell bash脚本注意:单行末尾转义符 \ 后千万不能有其他无关字符(多行命令)

MBA-day26 数的概念与性质

Qui vole dans un jeu d'écriture?

Win11安装权限在哪里设置?Win11安装权限设置的方法

正则表达式系列之手机号码正则

【U盘检测】为了转移压箱底的资料,买了个2T U盘检测仅仅只有47G~

【笔记】再笔记--边干边学Verilog HDL – 014

Classic illustration of K-line diagram (Collection Edition)

MySQL remote connection
随机推荐
有了这4个安全测试工具,对软件安全测试say so easy!
JVM(3) 类加载
What about frequent network disconnection of win11 system? Solution to win11 network instability
swift可选值总结
4-2端口Banner信息获取
微信推出图片大爆炸功能;苹果自研 5G 芯片或已失败;微软解决导致 Edge 停止响应的 bug|极客头条
洞见科技作为「唯一」隐私计算数商,「首批」入驻长三角数据要素流通服务平台
构建增强现实移动应用程序的六款顶级工具
AI场景存储优化:云知声超算平台基于 JuiceFS 的存储实践
高能直播,大咖云集!邀你共启BizDevOps探索之路。
mysql远程连接
k线图经典图解(收藏版)
Win11系统小组件打不开?Win11系统小组件无法打开解决方法
CAD Assistant - 3D模型格式转换利器
freeswitch拨打分机号
细说GaussDB(DWS)复杂多样的资源负载管理手段
php实现 提取不重复的整数(编程题目能够最快的熟悉函数)
7. cancellation and closing
Static static member variables use @value injection
Connaissance générale des paramètres de sécurité du serveur Cloud