23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list.
Analyze and describe its complexity.
Example
Given lists:
[
2->4->null,
null,
-1->null
],
return -1->2->4->null.
分析:
利用heap来保存数组中每一个list的第一个node, 当取出一个node以后,再把那个node的next node加进来,直到所有node都已被加进来。
1 class Solution { 2 public ListNode mergeKLists(ListNode[] lists) { 3 Queue<ListNode> heap = new PriorityQueue<ListNode>((n1, n2) -> n1.val - n2.val); 4 Arrays.stream(lists).filter(item -> item != null).forEach(item -> heap.add(item)); 5 6 ListNode head = new ListNode(-1); 7 ListNode cur = head; 8 while (heap.size() > 0) { 9 ListNode node = heap.poll(); 10 cur.next = node; 11 cur = node; 12 if (node.next != null) { 13 heap.add(node.next); 14 } 15 } 16 return head.next; 17 } 18 }

浙公网安备 33010602011771号