# LeetCode23. Merge k Sorted Lists（链表 / 模拟）

## LeetCode23. Merge k Sorted Lists（链表 / 模拟）

• Hard
• Accepted：456,754
• Submissions：1,262,052

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

### 链接

https://leetcode.com/problems/merge-k-sorted-lists

### 代码

• Runtime: 20 ms, faster than 98.89% of C++ online submissions for Merge k Sorted Lists.
• Memory Usage: 11.1 MB, less than 67.86% of C++ online submissions for Merge k Sorted Lists.
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
int n = lists.size();
if (n == 0)
return NULL;
while (n > 1)
{
for (int i = 0; i < n / 2; ++i)
lists[i] = mergeTwoLists(lists[i], lists[n - 1 - i]);
n = (n + 1) / 2;
}
return lists.front();
}

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
ListNode* dummy = new ListNode(-1);
ListNode* cur = dummy;
while (l1 && l2)
{
if (l1->val < l2->val)
{
cur->next = l1;
l1 = l1->next;
}
else
{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = (l1 ? l1 : l2);
return dummy->next;
}
};

The end.
2019年9月26日 星期四