File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ /* *
2+ * Definition for singly-linked list.
3+ * struct ListNode {
4+ * int val;
5+ * ListNode *next;
6+ * ListNode() : val(0), next(nullptr) {}
7+ * ListNode(int x) : val(x), next(nullptr) {}
8+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
9+ * };
10+ */
11+ typedef pair<int , ListNode*> pil;
12+ class Solution {
13+ public:
14+ ListNode* mergeKLists (vector<ListNode*>& lists) {
15+ priority_queue<pil, vector<pil>, greater<pil>> pq;// min-heap
16+ int k = lists.size ();
17+
18+ for (int i = 0 ; i < k; i++) {
19+ if (lists[i] != NULL )
20+ pq.push ({lists[i]->val , lists[i]});
21+ }
22+
23+ ListNode* dummy = new ListNode (0 );
24+ ListNode* curr = dummy;
25+
26+ while (!pq.empty ()) {
27+ auto top = pq.top ();
28+ pq.pop ();
29+
30+ // dummy updt
31+ curr->next = top.second ;
32+ curr = curr->next ;
33+
34+ // pq updt
35+ if (top.second ->next != NULL )
36+ pq.push ({top.second ->next ->val , top.second ->next });
37+ }
38+
39+ return dummy->next ;
40+ }
41+ };
You can’t perform that action at this time.
0 commit comments