Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists==null || lists.length==0) {
return null;
}
PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(lists.length, new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
if (o1.val < o2.val) {
return -1;
} else if (o1.val > o2.val) {
return 1;
} else {
return 0;
}
}
});
for (ListNode list : lists) {
if (list == null) {
continue;
}
queue.add(list);
}
ListNode head = new ListNode(0);
ListNode curNode = head;
while (!queue.isEmpty()) {
ListNode t = queue.poll();
curNode.next = t;
curNode = t;
if (t.next != null) {
queue.add(t.next);
}
}
return head.next;
}
}
本文介绍了一种使用优先队列合并K个已排序链表的方法,并提供了完整的Java实现代码。该方法首先将所有链表的头节点放入优先队列中,然后依次取出最小节点并加入到新的链表中,直至优先队列为空。
551

被折叠的 条评论
为什么被折叠?



