滑动窗口的最大值

滑动窗口的最大值

给定一个数组和滑动窗口的大小,请找出所有滑动窗口里的最大值。

例如,如果输入数组[2, 3, 4, 2, 6, 2, 5, 1]及滑动窗口的大小3,那么一共存在6个滑动窗口,它们的最大值分别为[4, 4, 6, 6, 6, 5]。

注意:

数据保证k大于0,且k小于等于数组长度。

样例
输入:[2, 3, 4, 2, 6, 2, 5, 1] , k=3
输出: [4, 4, 6, 6, 6, 5]

优先级队列

时间复杂度O(n)

class Solution {
    public int[] maxInWindows(int[] nums, int k) {
        if(nums.length == 0 || nums == null) {
            return nums;        
        }
        LinkedList<Integer> list = new LinkedList<Integer>();
        Queue<Integer> q = new PriorityQueue<Integer>(k,(a,b) -> b - a);
        for(int i = 0;i < k;i++) {
            q.offer(nums[i]);
        }
        for(int i = 0;i < nums.length - k + 1;i++) {
            list.add(q.peek());
            q.remove(nums[i]);
            if(i != nums.length - k) {
                q.offer(nums[i + k]);
            }
        }
        return list.stream().mapToInt(a -> a.intValue()).toArray();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值