Merge k Sorted Lists

来源:互联网 发布:ios wkwebview 传值js 编辑:程序博客网 时间:2024/04/30 11:55

Problem:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

最简单的方法是使用PriorityQueue。PriorityQueue是个基于优先级堆的极大优先级队列。
此队列按照在构造时所指定的顺序对元素排序,既可以根据元素的自然顺序来指定排序,
也可以根据 Comparator 来指定,这取决于使用哪种构造方法。

public ListNode mergeKLists(ListNode[] lists) {if (lists.length == 0)return null;//PriorityQueue is a sorted queuePriorityQueue<ListNode> q = new PriorityQueue<ListNode>(lists.length,new Comparator<ListNode>() {public int compare(ListNode a, ListNode b) {return a.val-b.val;}});//add first node of each list to the queuefor (ListNode list : lists) {if (list != null)q.add(list);}ListNode head = new ListNode(0);ListNode p = head; // serve as a pointer/cursorwhile (q.size() > 0) {ListNode temp = q.poll();//poll() retrieves and removes the head of the queue - q. p.next = temp;//keep adding next element of each listif (temp.next != null)q.add(temp.next);p = p.next;}return head.next;}


0 0
原创粉丝点击