当前位置:网站首页>Sword finger offer 59 - I. maximum value of sliding window
Sword finger offer 59 - I. maximum value of sliding window
2022-06-29 19:40:00 【Yake1965】
The finger of the sword Offer 59 - I. Maximum sliding window
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++){
// A monotonous queue
while (!q.isEmpty() && nums[i] >= nums[q.peekLast()]) {
q.pollLast();
}
q.add(i); // Indexes
int left = i - k + 1; // When left >= 0 Start sliding window when
if (q.peek() < left) q.poll();
if (left >= 0) res[left] = nums[q.peek()];
}
return res;
}
}
边栏推荐
猜你喜欢
MSYQL, redis, mongodb visual monitoring tool grafana

C语言数组专题训练

【网络方向实训】-企业园区网络设计-【Had Done】

Win11系统频繁断网怎么办?Win11网络不稳定的解决方法

电脑ssd硬盘怎么安装使用

Luoqingqi: has high-end household appliances become a red sea? Casati took the lead in breaking the game

How is the combination of convolution and transformer optimal?

Violent solution to the question of guessing the ranking

@Sneakythlows annotation

There is no small green triangle on the method in idea
随机推荐
JVM(3) 类加载
做白银k线图有多重要?
The era of data security solutions
QC协议+华为FCP+三星AFC快充取电5V9V芯片FS2601应用
KDD 2022 | 協同過濾中考慮錶征對齊和均勻性
After CDN is added to the website, the Font Icon reports an error access control allow origin
有了这4个安全测试工具,对软件安全测试say so easy!
剑指 Offer 41. 数据流中的中位数
@Sneakythlows annotation
虎符限币种提现 用户曲线出金即亏损
自动获取本地连接及网络地址修改
Canonical engineers are trying to solve the performance problem of Firefox snap
一小时构建示例场景 声网发布灵隼物联网云平台
k线图经典图解(收藏版)
逻辑结构与物理结构
细说GaussDB(DWS)复杂多样的资源负载管理手段
AI scene Storage Optimization: yunzhisheng supercomputing platform storage practice based on juicefs
freeswitch拨打分机号
KDD 2022 | 协同过滤中考虑表征对齐和均匀性
Creators foundation highlights in June