题目:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路:建立一个heap,将每个list的第一个node放入heap中,每次将堆顶的元素拿出来放到最终结果中。
class Solution {
public:
struct compare {
bool operator()(const ListNode* a, const ListNode* b) { //return true if Priority(A) < Priority(B)
return a->val > b->val; //the smaller one has higher priority
}
};
ListNode *mergeKLists(vector<ListNode *> &lists) {
priority_queue<ListNode*, vector<ListNode*>, compare> frontier;
for (int i = 0; i < lists.size(); ++i) {
if (lists[i] != nullptr) {
frontier.push(lists[i]);
}
}
ListNode dummy(0);
ListNode* runner = &dummy;
while (!frontier.empty()) {
runner->next = frontier.top();
runner = runner->next;
if (frontier.top()->next != nullptr) {
frontier.push(frontier.top()->next);
}
frontier.pop();
}
return dummy.next;
}
};
总结:最后一个放入结果中的元素必为某个list的结尾元素,因此不需要考虑去尾的问题。复杂度为O((n1 + n2 + ...) log k). ni为第i个list的长度。