题目:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 方法一:逐个比较,合并两个链表的方法,time exceeded limited
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
vector<ListNode*> p_lists = lists;
ListNode* Head = new ListNode(0,p_lists[0]);
ListNode* prev = Head;
while(1){
int minL = INT_MAX;
int index = 0;
for(int i = 0; i < p_lists.size(); i++)
{
if(p_lists[i] != NULL && minL > p_lists[i]->val)
{
minL = p_lists[i]->val;
index = i;
}
}
if(minL == INT_MAX)
break;
if(index == 0)
{
p_lists[0] = p_lists[0]->next;
prev = prev->next;
}
else
{
p_lists[index] = p_lists[index]->next;
p_lists[index]->next = p_lists[0];
prev->next = p_lists[index];
prev = prev->next;
}
}
return Head->next;
}
};
方法二: 暴力破解,遍历所有节点,把节点的值放进数组里,对数组进行排序,然后创建一个链表,将数组里面的值依次放进链表里面
方法三:通过优先队列,对上面的代码进行优化,先把链表的首节点都入队列,队列头部为最小节点,取出添加在新链表头后面,之后将取出的节点的后继再入队列,如此循环,直到队列为空(队列使用参考:优先队列)
class Solution {
public:
struct CMPL{
bool operator()(const ListNode* L1,const ListNode* L2)
{
return L1->val > L2->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*,vector<ListNode*>,CMPL> Q;
for(int i = 0; i < lists.size(); i++)
{
if(lists[i])
Q.push(lists[i]);
}
ListNode* Head = new ListNode(0);
ListNode* prev = Head;
while(!Q.empty())
{
ListNode* node = Q.top();
Q.pop();
prev->next = node;
prev = prev->next;
if (node->next != NULL){
Q.push(node->next);
}
}
return Head->next;
}
};