Difficulty:: Hard
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
1 2 3 4 5 6 7
| Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6
|
Solution
Language: Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
class Solution { public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) { return null; } ListNode dummy = new ListNode(0); ListNode cur = dummy; PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val); for (ListNode l : lists) { if (l == null) { continue; } pq.offer(l); } while (!pq.isEmpty()) { ListNode tmp = pq.poll(); cur.next = tmp; cur = cur.next; if (tmp.next != null) { pq.offer(tmp.next); } } return dummy.next; } }
|
或者可以用归并排序的方法