Skip to content

Commit

Permalink
[LeetCode] Add January 24.
Browse files Browse the repository at this point in the history
  • Loading branch information
pin3da committed Jan 24, 2021
1 parent eb63346 commit 08ac8bd
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions solved/LeetCode/Challenges/2020/January/24.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <bits/stdc++.h>

using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
set<pair<int, ListNode*>> bestList;
for (auto it : lists) {
if (it != nullptr) {
bestList.insert(make_pair(it->val, it));
}
}

ListNode* head = nullptr;
ListNode* cur = nullptr;
while (bestList.size() > 0) {
ListNode* first = bestList.begin()->second;
ListNode* next = first->next;
bestList.erase(bestList.begin());
if (head == nullptr) {
head = first;
cur = first;
} else {
cur->next = first;
cur = first;
}
if (next != nullptr) {
bestList.insert(make_pair(next->val, next));
}
}
return head;
}
};

0 comments on commit 08ac8bd

Please sign in to comment.