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
解题思路:两个有序链表的话,我们都会排列,所以这里可以两两合并。最暴力的解法,将第一个链表不停地与其他链表进行合并。
C++
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size()==0){
ListNode *l;
l=new ListNode(0);
return l->next;
}
for(int i=1;i<lists.size();i++){
lists[0]=mergeTwoLists(lists[0], lists[i]);
}
return lists[0];
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head,*temp,*p,*q;
head=new ListNode(0);
temp=head;
p=l1;q=l2;
while(p!=NULL&&q!=NULL){
if(p->val<=q->val){
temp->next=p;
temp=temp->next;
p=p->next;
}
else{
temp->next=q;
temp=temp->next;
q=q->next;
}
}
if(p!=NULL)
temp->next=p;
if(q!=NULL)
temp->next=q;
return head->next;
}
};
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if not lists:
return None
def mergeTwoLists(l1, l2):
p, q, ans = l1, l2, ListNode(0)
r = ans
while p and q:
if p.val > q.val:
p, q = q, p
r.next = p
p, r = p.next, r.next
if q:
r.next = q
else:
r.next = p
return ans.next
for i in range(1, len(lists)):
lists[0] = mergeTwoLists(lists[0], lists[i])
return lists[0]
优化一下,不难发现,上述解法的效率太低,按哈夫曼树的思想,每次取两个待排序中长度最短的链表进行合并,此时的效率比较高,但是我们不能知道所有链表的长度,所以这里用一种近似解法,即归并排序,先每两个链表进行合并,然后得到的链表再进行两两合并,以此类推。
C++
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() == 0)
return NULL;
int length = lists.size();
int interval = 1;
while(interval < length){
for(int i = 0; i < length - interval; i += interval * 2)
lists[i] = mergeTwoLists(lists[i], lists[i + interval]);
interval <<= 1;
}
return lists[0];
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head,*temp,*p,*q;
head = new ListNode(0);
temp = head;
p = l1;q = l2;
while(p!=NULL&&q!=NULL){
if(p->val<=q->val){
temp->next=p;
temp=temp->next;
p=p->next;
}
else{
temp->next=q;
temp=temp->next;
q=q->next;
}
}
if(p!=NULL)
temp->next=p;
if(q!=NULL)
temp->next=q;
return head->next;
}
};
Python
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if not lists:
return None
def mergeTwoLists(l1, l2):
p, q, ans = l1, l2, ListNode(0)
r = ans
while p and q:
if p.val > q.val:
p, q = q, p
r.next = p
p, r = p.next, r.next
if q:
r.next = q
else:
r.next = p
return ans.next
interval = 1
while interval < len(lists):
for i in range(0, len(lists) - interval, 2 * interval):
lists[i] = mergeTwoLists(lists[i], lists[i + interval]);
interval <<= 1;
return lists[0]