题目描述:
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
Java代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode dummy = new ListNode(0);
ListNode head = dummy;
PriorityQueue<ListNode> pq = new PriorityQueue<>((o1, o2) -> Integer.compare(o1.val, o2.val));
for(ListNode l : lists) {
if(l != null) pq.add(l);
}
while(!pq.isEmpty()) {
ListNode curr = pq.poll();
head.next = curr;
head = head.next;
if(curr.next != null) pq.add(curr.next);
}
return dummy.next;
}
}
网友评论