Collections.sort() vs. PriorityQueue

  • Collections.sort() is merge sort. If you have already had a List of things to sort, you can apply Collections.sort() to that as Arrays.sort() for an array.
  • PrioirtyQueue is heap sorting, which entails copying all the references and computing a heap before you can start polling. And it means copying references into another List data structure.
  • PriorityQueue is not meant for sorting, but meant for getting the highest priority element in a changing queue. It also does not improve performance nor does it make your code readable to sort using a PriorityQueue. I would therefore advise you to stick with Collections.sort() when it comes to sorting.

总之,Collectons.sort给你一个sort好的list,PriorityQueue一直给你树的顶端。那么,如何使用这俩呢。请看下面例子

共同的部分,两者都首先定义Comparator类,然后覆盖原来的int compare函数

Comparator<ListNode> comparator = new Comparator<ListNode>(){
    public int compare(ListNode list1, ListNode list2){
        int val1 = list1.val;
        int val2 = list2.val;
        return val1-val2;
    }
};   //别忘了这里的分号

然后,对 Collections.sort来说 (可见 Merge Intervals)

Collections.sort(list, comparator);

对PrioirtyQueue来说 (可见 Merge k sorted lists)

PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(lists.length, comparator);

results matching ""

    No results matching ""