您的位置:首页 > 其它

[LeetCode]Merge k Sorted Lists

2014-05-20 13:59 267 查看
Merge k sorted
linked lists and return it as one sorted list. Analyze and describe its complexity.

/**
* 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.size() == 0)
{
return NULL;
}
if (lists.size() == 1)
{
return lists[0];
}

int pos = 0;
int count = 0;

for (int i = 0; i < lists.size(); i++)
{
ListNode* p = lists[i];
while(p != NULL)
{
count++;
p = p->next;
}
}
if (count > 0)
{
ListNode* ans = new ListNode(0);
ListNode* ansTemp= ans;
while(count)
{
int min = INT_MAX;
for (int i = 0; i < lists.size(); i++)
{
if (lists[i] != NULL)
{
if ( (*lists[i]).val < min)
{
min = (*lists[i]).val;
pos = i;
}
}
}
ansTemp->val = (*lists[pos]).val;
if (count > 1)
{
ansTemp->next = new ListNode(0);
ansTemp = ansTemp->next;
}
lists[pos] = lists[pos]->next;
count--;
}
return ans;
}
else
{
return lists[0];
}
}
};


网上看到使用优先队列做的:

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
struct comp
{
//优先队列中默认是less(<),top为最大的元素
//此处为greater(>),top为最小元素
bool operator() (ListNode *a,ListNode *b)
{
return a->val > b->val;
}
};
ListNode *mergeKLists(vector<ListNode *> &lists)
{
ListNode *tmphead = new ListNode(0), *p = tmphead;
std::priority_queue<ListNode*,  std::vector<ListNode*>,  comp> q;
for(int i = 0; i < lists.size(); i ++)
{
if(lists[i] != NULL)
{
q.push(lists[i]);
}
}
while(!q.empty())
{
p->next = q.top();
p = p->next;
q.pop();
if(p ->next != NULL)
{
q.push(p->next);
}
}
return tmphead->next;
}
};


优先队列的介绍:

/article/9177854.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: