首页 > 编程知识 正文

java队列queue实现,滑动窗口的最大值java

时间:2023-05-04 19:28:15 阅读:161033 作者:664

输入整数数组arr,找到其中最小的k个。 例如,如果输入8个数字: 4、5、1、6、2、7、3和8,则最小的4个数字为1、2、3和4。

以上述问题为背景。

1 .大顶堆创建大顶堆并运行poll ()时,删除的是大数,剩下的是小数。 构建方法(w1,w2 )- w2 - w1 //第二参数第一个是大山

import java.util.*; public class solution { publicstaticvoidmain (string [ ] args ) int [ ] arr=new int } { 3,2,1,6,9 }; int[]RES=getleastnumbers(ARR,4 ); system.out.println (arrays.tostring (RES ) ); }公共静态int [ ] getleastnumbers (int [ ] arr,int k ) ) priorityqueueintegerheap=newpriorityqueue ((w1,w2 )-w2fff if(heap.size ) ) k ) heap.poll ); } int[] res=new int[k]; int j=0; while (! heap.isEmpty () ) { res[j ]=heap.poll; } return res; }在堆中创建所有数组后,堆中的数据将如下所示:

然后,heap.poll ) )时,团队中会出现较大的数字,剩下的就是较小的数据。

2 .创建微型堆PriorityQueue使用缺省值创建微型堆

poll ) )时,会将值较小的数据出队,保留值较大的数据

import java.util.*; public class solution { publicstaticvoidmain (string [ ] args ) int [ ] arr=new int } { 3,2,1,6,9 }; int[]RES=getleastnumbers(arr,3 ); system.out.println (arrays.tostring (RES ) ); } public static int [ ] getleastnumbers (int [ ] arr,int k ) (priorityqueueintegerheap=newpriorityqueue ); for(intvalue:arr ) HEAP.offer ) value; if(heap.size ) ) k ) heap.poll ); } int[] res=new int[k]; int j=0; while (! heap.isEmpty () ) { res[j ]=heap.poll; } return res; }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。