Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example
Given lists:
[
2->4->null,
null,
-1->null
],
return -1->2->4->null
.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
思路:这个题有两个点需要注意,首先,链表已经是有序的,所以不需要对链表进行排序,其次,链表的数组中有N多个链表,难以一次解决,但是如果只有两个链表就很容易归并了,所以思路依旧是分而治之。
用二分法将链表数组划分直到只剩下两个链表,合并这两个链表,返回一个总的头结点(这个链表就是归并之后的前两个链表),再拿这个链表和第三个继续归并,直到最后归并到只有一个头结点结束。
代码中有两个函数,第一个函数sortList其实就是将链表数组分到只剩下两个链表,然后调用第二个函数merge2Lists合并这两个链表。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge2Lists(ListNode* l1, ListNode* l2) {
if (l2 == NULL && l1 == NULL) return NULL;
if (l1 == NULL && l2 != NULL) return l2;
if (l2 == NULL && l1 != NULL) return l1;
ListNode* dummy = new ListNode(0);
ListNode* temp = dummy;
while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
temp->next = l1;
l1 = l1->next;
} else {
temp->next = l2;
l2 = l2->next;
}
temp = temp->next;
}
if (l1 != NULL) temp->next = l1;
if (l2 != NULL) temp->next = l2;
return dummy->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.size() == 0) return NULL;
return merge(lists, 0, lists.size() - 1);
}
ListNode* merge(vector<ListNode*>& lists, int start, int end) {
if (start == end) return lists[start];
if (start > end) return NULL;
int mid = (start + end) / 2;
ListNode* l1 = merge(lists, start, mid);
ListNode* l2 = merge(lists, mid + 1, end);
return merge2Lists(l1, l2);
}
};