Question
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Solution
-
归并排序中的Merge过程。
-
时间复杂度: 节点数目*k
Code
/**
* 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) {
int size = lists.size();
if (size == 0)
return NULL;
if (size == 1)
return lists[0];
ListNode* head = new ListNode(-1);
ListNode* pNode = head;
while (1) {
bool flag = false;
int index;
int cur = INT_MAX;
for (int i = 0; i < size; i++) {
if (lists[i] != NULL) {
flag = true;
if (lists[i]->val < cur) {
cur = lists[i]->val;
index = i;
}
}
}
if (flag == false)
break;
pNode->next = lists[index];
pNode = lists[index];
lists[index] = lists[index]->next;
}
return head->next;
}
};