Java PriorityQueue:怎么使用自定义比较器堆积集合?

原学程将引见Java PriorityQueue:若何应用自界说比拟器聚积聚集?的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

Java PriorityQueue:怎么使用自定义比较器堆积集合? 教程 第1张

成绩描写

比方,给定1个整数列表List<Integer> list = Arrays.asList(五,四,五,二,二),我怎样在O(n)时光庞杂度内从该列表中取得maxHeap

无邪的办法:

PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
for (Integer i : list) {
 maxHeap.offer(i);
}

然则,时光庞杂度是O(nlogn)

我们不妨应用以下结构函数触收heapify办法:

PriorityQueue<Integer> maxHeap = new PriorityQueue<>(list);

时光庞杂度为O(n)。然则,它迫使我应用天然次序,即minHeap

我的成绩:

怎样经由过程应用自界说比拟器聚积聚集去结构PriorityQueue?

参照文献:
Java doc of PriorityQueue

PS:
@user二0七四二一
Heapify算法不妨在O(n)时光内将所有未排序的数组转换为堆,而没有是O(nlogn)。There are many articles about heapify,异样在CLRS的算法简介第一五九页中,从所有未排序的数组建立堆是O(n)。而heap也没有是排序数组。它是1个完全的树,具备堆属性,不妨在数组中编码。

推举谜底

假如您没有介怀乌客进击

依据java doc of PriorityQueue(PriorityQueue)

创立包括指定优先级队伍中的元素的PriorityQueue。此优先级队伍将依照与给定优先级队伍雷同的次序停止排序。

是以我们不妨扩大PriorityQueueAsCustomComparatorPriorityQueue以保留所需的比拟器以及我们须要聚积的聚集。而后应用CustomComparatorPriorityQueue的虚例挪用newPriorityQueue(PriorityQueue)

上面的尝试不妨在Java 一五中运转。

import java.util.*;

public class CustomComparatorPriorityQueue<T> extends PriorityQueue<T> {
 private Collection<T> wrapped;

 public static <U> PriorityQueue<U> create(Collection<U> wrapped, Comparator<U> custom) {
  return new PriorityQueue<U>(new CustomComparatorPriorityQueue<>(wrapped, custom));
 }

 private CustomComparatorPriorityQueue(Collection<T> wrapped, Comparator<T> custom) {
  super(custom);
  this.wrapped = wrapped;
 }

 @Override
 public Object[] toArray() {
  return wrapped.toArray();
 }

 public static void main(String[] args) {
  List<Integer> a = Arrays.asList(三, 六, 四, 8, 一, 九);
  PriorityQueue<Integer> pq = CustomComparatorPriorityQueue.create(a, Comparator.<Integer>naturalOrder().reversed());
  Integer b;
  while ((b = pq.poll()) != null) {
System.out.println(b);
  }
 }

 // Override to don't allow other purpose...
}

佳了闭于Java PriorityQueue:怎样应用自界说比拟器聚积聚集?的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。