当前位置:网站首页>剑指 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;
}
}
边栏推荐
- 建立自己的网站(12)
- Win11 system component cannot be opened? Win11 system widget cannot be opened solution
- One hour to build a sample scenario sound network to release lingfalcon Internet of things cloud platform
- The developer task center is online! Thousands of yuan of gifts!
- Why is informatization ≠ digitalization? Finally someone made it clear
- 3-3主機發現-四層發現
- 福昕软件受邀亮相2022先进制造业数智发展论坛
- nacos 问题
- 3-3主机发现-四层发现
- 7.取消与关闭
猜你喜欢

深度好文 | YOLOv5+DeepSORT多目标跟踪深入解读与测试(含源码)

Game Maker 基金会呈献:归属之谷

细说GaussDB(DWS)复杂多样的资源负载管理手段

QC协议+华为FCP+三星AFC快充取电5V9V芯片FS2601应用

Qui vole dans un jeu d'écriture?

Physical verification LVS process and Technology (Part I)

JVM(2) 垃圾回收

Win11 system component cannot be opened? Win11 system widget cannot be opened solution

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

Game maker Foundation presents: Valley of belonging
随机推荐
k线图经典图解(收藏版)
shell bash脚本注意:单行末尾转义符 \ 后千万不能有其他无关字符(多行命令)
freeswitch拨打分机号
jfinal中如何使用过滤器监控Druid监听SQL执行?
【剑指Offer】51. 数组中的逆序对
Qui vole dans un jeu d'écriture?
4-1端口扫描技术
MySQL remote connection
云服务器的安全设置常识
[software testing] 01 -- software life cycle and software development model
3-3主機發現-四層發現
数据安全解决方案的大时代
做白银k线图有多重要?
以其他组件为代价的性能提升不是好提升
JVM (2) garbage collection
PHP Laravel 使用 aws 负载均衡器的 ip 错误问题
Arm comprehensive computing solution redefines visual experience and powerfully enables mobile games
KDD 2022 | 协同过滤中考虑表征对齐和均匀性
The concept and properties of mba-day26 number
一个mysql里有3306端口下,一个mysql有20多个数据库,怎么一键备份20多个数据库,做系统备份,防止数据误删除?