原题链接:
https://leetcode.com/problems/merge-k-sorted-lists/description/
题意理解
要将n个已排序好的list拼接成一个有序的list,此处的有序均是从小到大。
我的代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty()) {
return nullptr;
}
priority_queue<int, vector<int>, greater<int>> pq;
int sz = (int)lists.size();
for(int i = 0; i < sz; i++) {
for(auto it = lists[i]; it; it = it->next) {
pq.push(it->val);
}
}
ListNode* fake = new ListNode(-1);
ListNode* tmp = fake;
while(!pq.empty()) {
ListNode* l1 = new ListNode(pq.top());
tmp->next = l1;
tmp = tmp->next;
pq.pop();
}
return fake->next;
}
};
别人最快的代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
static const auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* newHead = nullptr;
ListNode* newEnd = nullptr;
auto compareNodes = [](ListNode* a, ListNode* b) {
if (a == nullptr) return false;
else if (b == nullptr) return true;
return a->val > b->val;
};
make_heap(lists.begin(), lists.end(), compareNodes);
while (!lists.empty()) {
pop_heap(lists.begin(), lists.end(), compareNodes);
if (lists.back() == nullptr) {
lists.pop_back();
continue;
}
if (newHead == nullptr) {
newHead = lists.back();
newEnd = lists.back();
} else {
newEnd->next = lists.back();
newEnd = newEnd->next;
}
if (lists.back()->next == nullptr) {
lists.pop_back();
} else {
lists[lists.size() - 1] = lists.back()->next;
push_heap(lists.begin(), lists.end(), compareNodes);
}
}
return newHead;
}
};
主要区别在于,别人是直接把ListNode*来比较,heap的大小会小一些,所以可能会快一点,但是写起来没有那么简单对不对。