今天在做347.前K个高频元素时,需要用到最小堆,实现如下:
PriorityQueuequeue = new PriorityQueue (new Comparator () { public int compare(int[] m,int[] n) { return m[1] - n[1]; } });
其中m在前,n在后,表示为升序排列,即从小到大,最小的在最前面,栈顶即最小元素。
若堆中元素为int类型,则代码为:
PriorityQueuequeue = new PriorityQueue (new Comparator () { public int compare(Integer m,Integer n) { return n - m; } });
此时return n - m;即实现了一个最大堆。
另外,在容器中添加int[]数组时,可以采用new int[]{a,b}的方式来快速构造。
如:
queue.offer(new int[]{num,count});



