看了网上的讲解
Merge k sorted
linked lists and return it as one sorted list. Analyze and describe its complexity.
一开始想一个一个去合并,复杂度是 O(nk), n 是所有元素的个数。
使用归并排序的思想,可以降到 o(n*log(k)).
代码参考了网上的,写的很好,得学会
merge 就相当于得到已经排序好了的, mergeTwoLists 是合并
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param a list of ListNode
# @return a ListNode
def mergeTwoLists(self, l1, l2):
tra,trb = l1,l2
trc = ListNode(1000)
prehead = trc
while True:
if tra==None:
trc.next = trb
return prehead.next
if trb==None:
trc.next = tra
return prehead.next
if tra.val<=trb.val:
trc.next = tra
tra = tra.next
else:
trc.next = trb
trb = trb.next
trc = trc.next
def merge(self,lists,l,r):
if l<r:
m = (l+r)/2
return self.mergeTwoLists(self.merge(lists,l,m),self.merge(lists,m+1,r))
return lists[l]
def mergeKLists(self, lists):
if len(lists)==0:
return None
return self.merge(lists,0,len(lists)-1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode *tra, *trb, *prehead;
tra = l1;
trb = l2;
ListNode *trc = new ListNode(100);
prehead = trc;
while (true){
if (tra==NULL){
trc->next = trb;
return prehead->next;
}
if (trb==NULL){
trc->next = tra;
return prehead->next;
}
if (tra->val<=trb->val){
trc->next = tra;
trc = tra;
tra = tra->next;
}
else{
trc->next = trb;
trc = trb;
trb = trb->next;
}
}
}
ListNode *merge(vector<ListNode *> &lists, int l, int r){
if (l<r){
int m = (l+r)/2;
return mergeTwoLists(merge(lists,l,m),merge(lists,m+1,r));
}
return lists[l];
}
ListNode *mergeKLists(vector<ListNode *> &lists) {
if (lists.size()==0){
return NULL;
}
return merge(lists,0,lists.size()-1);
}
};