leetcode 23合并K个排序链表(merge-k-sorted-lists)
使用堆排序构造一个优先队列可以轻松解决,一直以来了解堆排序但没有实际写过,这次大概写了一个半成品,用来做这道题足够了。
//c++版本
class Heap {
private:
int size;
vector<ListNode*> ptrs;
public:
Heap(vector<ListNode*> list)
{
for(int i =0;i<list.size();i++)
{
if(list[i])
ptrs.push_back(list[i]);
}
size = ptrs.size();
}
void minHeapfy(int i)
{
int left = 2 * i + 1;
int right = 2 * i + 2;
ListNode* temp;
int ind = i;
if (left < size && ptrs[left]->val < ptrs[ind]->val)
{
ind = left;
}
if (right < size&&ptrs[right]->val < ptrs[ind]->val)
ind = right;
if (ind != i)
{
temp = ptrs[i];
ptrs[i] = ptrs[ind];
ptrs[ind] = temp;
minHeapfy(ind);
}
}
void HeapSort()
{
for (int i = (size - 2) / 2; i >= 0; i--)
{
minHeapfy(i);
}
}
int extractmin()
{
int res = ptrs[0]->val;
if(ptrs[0]->next==NULL)
{
ptrs[0] = ptrs[size-1];
size -= 1;
}
else
{
ptrs[0] = ptrs[0]->next;
}
minHeapfy(0);
return res;
}
int getsize()
{
return size;
}
};
/**
* 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 NULL;
Heap heap(lists);
if(heap.getsize()==0)
return NULL;
ListNode* res=NULL;
ListNode* ptr=NULL;
int flag = 0;
heap.HeapSort();
while(heap.getsize()!=0)
{
ListNode* node = new ListNode(heap.extractmin());
if(!flag)
{
res = ptr = node;
flag = 1;
}
else
{
ptr->next = node;
ptr = node;
}
}
return res;
}
};