LeetCode 23 Merge k Sorted Lists (C++, Python)
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Solution C++
Solution Python
Solution C++
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 37 38 39 40 41 42 43 44 45 46 47 | /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ struct NodeComp { bool operator ()(const pair<int, ListNode*> n1, const pair<int, ListNode*> n2) { return n1.second->val > n2.second->val; } }; class Solution { public: ListNode *mergeKLists(vector<ListNode *> &lists) { ListNode* newHead = NULL; ListNode* newTail = NULL; if (lists.size() == 0) return newHead; priority_queue<pair<int, ListNode*>, vector<pair<int, ListNode*>>, NodeComp> myqueue; for (int i = 0; i < lists.size(); ++i) { ListNode* head = lists[i]; if (head) { lists[i] = head->next; head->next = NULL; myqueue.push({i, head}); } } while (!myqueue.empty()) { pair<int, ListNode*> node = myqueue.top(); myqueue.pop(); if (newHead) { newTail->next = node.second; newTail = node.second; } else { newHead = newTail = node.second; } ListNode* head = lists[node.first]; if (head) { lists[node.first] = head->next; head->next = NULL; myqueue.push({node.first, head}); } } return newHead; } }; |
Solution Python
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 | # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None import heapq class Solution: # @param a list of ListNode # @return a ListNode def mergeKLists(self, lists): newHead = None newTail = None if not lists: return newHead h = [] for i in range(len(lists)): head = lists[i] if not head: continue lists[i] = head.next head.next = None heapq.heappush(h, (head.val, i, head)) while h: v, i, n = heapq.heappop(h) if newHead: newTail.next = n newTail = n else: newHead = newTail = n head = lists[i] if not head: continue lists[i] = head.next head.next = None heapq.heappush(h, (head.val, i, head)) return newHead |