23. Merge k Sorted Lists
题目
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
解析
- 本题解题思路很多
- 使用堆make_heap,或者优先队列
- 使用堆,分治,归并等
class Solution_23 {
public:
struct CompareListNode
{
bool operator()(ListNode* a, ListNode* b)
{
return a->val > b->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* head = new ListNode(0);
ListNode* cur = head;
priority_queue<ListNode*, vector<ListNode*>,CompareListNode> head_que; //元素是struct,class时,比较函数也要用对应的类型 //对于算法类型的函数调用sort();cmp使用函数即可
for (int i = 0; i < lists.size();i++)
{
if (lists[i]) //非空入堆
{
head_que.push(lists[i]); //建立堆
}
}
while (head_que.size()>0)
{
ListNode* temp = head_que.top(); //取堆顶元素
head_que.pop();
cur->next = temp;
cur = cur->next;
if (temp->next)
{
head_que.push(temp->next);
}
}
cur->next = NULL;
return head->next;
}
};
题目来源