zoukankan      html  css  js  c++  java
  • 滑动窗口的最大值

    给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。

    java:

     1 import java.util.*;
     2 public class Solution {
     3     public ArrayList<Integer> maxInWindows(int [] num, int size)
     4     {
     5         PriorityQueue<Integer> heap = new PriorityQueue<Integer>((o1,o2) -> o2-o1) ;
     6         ArrayList<Integer> res = new ArrayList<Integer>() ;
     7         if (num.length == 0 || size == 0 || num.length < size){
     8             return res ;
     9         }
    10         for(int i = 0 ; i < size ; i++){
    11             heap.add(num[i]) ;
    12         }
    13         res.add(heap.peek()) ;
    14         for(int i = 0 , j = i + size ; j < num.length ; i++ , j++){
    15             heap.remove(num[i]) ;
    16             heap.add(num[j]) ;
    17             res.add(heap.peek()) ;
    18         }
    19         return res ;
    20     }
    21 }
  • 相关阅读:
    maven只编译某个module
    idea中java文件不显示成class标识符
    服务系统要点
    shell命令
    shell中的exit
    性能统计方法
    聚类
    java 外部类可以访问嵌套类的私有成员
    SqlServer动态生成临时表
    优化JavaScript脚本的性能(转载)
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/10583674.html
Copyright © 2011-2022 走看看