LeetCode 23. Merge k Sorted Lists
题目
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
分析
把k个排列好的链表合并成一个返回,根据链表的特性,我决定采取以下策略:
使用插入排序
把其他链表插入第一个不为NULL的链表
不过感觉复杂度有点高为O(k^2 * n)…
代码实现
class Solution {
public:
ListNode * mergeKLists(vector<ListNode*>& lists) {
if (lists.size() == 0)return nullptr;
int first = 0;
while (lists[first] == nullptr)
{
first++;
if (first == lists.size())return nullptr;
}
for (int index = first + 1; index < lists.size(); index++)
lists[first] = mergeTwoLists(lists[first], lists[index]);
return lists[first];
}
private:
//把l2合并到l1
ListNode* mergeTwoLists(ListNode *l1, ListNode *l2) {
if (l2 == nullptr)return l1;
//保证l1->val < l2->val
if (l1->val > l2->val) {
ListNode *temp = l2;
l2 = l1;
l1 = temp;
}
//p储存l1的头部
ListNode *p = l1;
/*l2插入l1*/
while (l2 != nullptr)
{
ListNode *save;
save = l2->next;
insertValue(l1, l2);
l2 = save;
}
return p;
}
void insertValue(ListNode *l1, ListNode *value)
{
//本函数会修改value指向位置,因此在调用前需保存value->next
if (l1->next == nullptr)
{
l1->next = value;
value->next = nullptr;
return;
}
while (value->val >= l1->next->val)
{
l1 = l1->next;
if (l1->next == nullptr)
{
l1->next = value;
value->next = nullptr;
return;
}
}
ListNode *save;
save = l1->next;
l1->next = value;
value->next = save;
}
};