File tree 1 file changed +44
-0
lines changed
1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ 23. Merge k Sorted Lists
3
+
4
+ Submitted: December 12, 2024
5
+
6
+ Runtime: 0 ms (beats 100.00%)
7
+ Memory: 18.28 MB (beats 84.05%)
8
+ */
9
+
10
+ /* *
11
+ * Definition for singly-linked list.
12
+ * struct ListNode {
13
+ * int val;
14
+ * ListNode *next;
15
+ * ListNode() : val(0), next(nullptr) {}
16
+ * ListNode(int x) : val(x), next(nullptr) {}
17
+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
18
+ * };
19
+ */
20
+ class Solution {
21
+ public:
22
+ ListNode* mergeKLists (vector<ListNode*>& lists) {
23
+ auto cmp = [](ListNode* a, ListNode* b) { return std::greater<int >()(a->val , b->val ); };
24
+ priority_queue<ListNode*, vector<ListNode*>, decltype (cmp)> pq;
25
+ for (ListNode* list : lists) {
26
+ if (list != nullptr ) pq.push (list);
27
+ }
28
+ ListNode* newHead = nullptr ;
29
+ ListNode* newTail = nullptr ;
30
+ while (!pq.empty ()) {
31
+ ListNode* p = pq.top ();
32
+ pq.pop ();
33
+ if (p->next != nullptr ) pq.push (p->next );
34
+ if (newHead == nullptr ) {
35
+ newHead = p;
36
+ newTail = p;
37
+ } else {
38
+ newTail->next = p;
39
+ newTail = newTail->next ;
40
+ }
41
+ }
42
+ return newHead;
43
+ }
44
+ };
You can’t perform that action at this time.
0 commit comments