归并 两两inplace merge O(nlogk) k是lists数 n是所有node数 O(1) space
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 class Solution : def mergeKLists (self, lists: List[ListNode] ) -> ListNode: if not lists: return None def merge (a, b ): tail = dummy = ListNode() while a and b: if a.val < b.val: tail.next = a a = a.next else : tail.next = b b = b.next tail = tail.next tail.next = a if a else b return dummy.next step, n = 1 , len (lists) while step < n: for i in range (0 , n, step << 1 ): if i + step >= n: break lists[i] = merge(lists[i], lists[i + step]) step <<= 1 return lists[0 ]
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 34 35 class Solution {public : ListNode* mergeKLists (vector <ListNode*>& lists) { if (lists.empty()) return nullptr ; auto merge = [](auto a, auto b) { ListNode dummy_head(0 ), *tail = &dummy_head; while (a && b) { if (a->val < b->val) { tail->next = a; a = a->next; } else { tail->next = b; b = b->next; } tail = tail->next; } tail->next = a ? a : b; return dummy_head.next; }; for (int n = lists.size(), step = 1 ; step < n; step <<= 1 ) { for (int i = 0 ; i + step < n; i += (step << 1 )) { lists[i] = merge(lists[i], lists[i + step]); } } return lists[0 ]; } };
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 34 35 36 class Solution {public : ListNode* mergeKLists (vector <ListNode*>& lists) { if (lists.empty()) return nullptr ; for (int n = lists.size(), step = 1 ; step < n; step <<= 1 ) { for (int i = 0 ; i + step < n; i += (step << 1 )) { lists[i] = merge(lists[i], lists[i + step]); } } return lists[0 ]; } ListNode *merge (ListNode *a, ListNode *b) { ListNode dummy_head(0), *tail = &dummy_head; while (a && b) { if (a->val < b->val) { tail->next = a; a = a->next; } else { tail->next = b; b = b->next; } tail = tail->next; } tail->next = a ? a : b; return dummy_head.next; } };
external sort O(nlogk) n is the number of all nodes, k is the number of linked lists
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 from queue import PriorityQueueListNode.__lt__ = lambda x, y: x.val < y.val class Solution : def mergeKLists (self, lists: List[ListNode] ) -> ListNode: q = PriorityQueue() for l in lists: if l: q.put(l) tail = dummy = ListNode() while not q.empty(): l = q.get() tail.next = l tail = l l = l.next if l: q.put(l) return dummy.next
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 class Solution {public : ListNode* mergeKLists (vector <ListNode*>& lists) { auto cmp = [](const auto &a, const auto &b) { return a->val > b->val; }; priority_queue <ListNode *, vector <ListNode *>, decltype (cmp)> q(cmp); for (auto l : lists) { if (l) { q.push(l); } } ListNode dummy_head(0), *tail = &dummy_head; while (!q.empty()) { auto l = q.top(); q.pop(); tail->next = l; tail = l; l = l->next; if (l) { q.push(l); } } return dummy_head.next; } };