Description
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
分析一
题目的意思是:k个有序链表合并。
- 归并排序,分治法,把多路归并转换为二路归并。
代码一
/**
* 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) {
if(lists.size()==0){
return NULL;
}
int n=lists.size();
while(n>1){
int k=(n+1)/2;
for(int i=0;i<n/2;i++){
lists[i]=mergeTwoLists(lists[i],lists[k+i]);
}
n=k;
}
return lists[0];
}
ListNode* mergeTwoLists(ListNode* l1,ListNode* l2){
ListNode* dump=new ListNode(-1);
ListNode* cur=dump;
while(l1&&l2){
if(l1->val<l2->val){
cur->next=l1;
l1=l1->next;
}else{
cur->next=l2;
l2=l2->next;
}
cur=cur->next;
}
if(l1){
cur->next=l1;
}
if(l2){
cur->next=l2;
}
return dump->next;
}
};
下面是python3版本的写法:
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
n = len(lists)
if not lists:
return None
i = 1
while n > 1:
k = (n+1)//2
for i in range(n//2):
lists[i]=self.mergeTwoLists(lists[i], lists[k+i])
n=k
return lists[0]
def mergeTwoLists(self, l1, l2):
dummy = ListNode()
p = dummy
while l1 and l2:
if l1.val<=l2.val:
p.next = l1
l1 = l1.next
else:
p.next = l2
l2 = l2.next
p = p.next
if l1:
p.next = l1
if l2:
p.next = l2
return dummy.next
分析二
- 最小堆,用优先级队列来进行模拟,自定义里面的compare函数,即自定义升序。
代码二
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct cmp {
bool operator () (ListNode *a, ListNode *b) {
return a->val > b->val;
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
priority_queue<ListNode*,vector<ListNode*>,cmp> q;
for(int i=0;i<lists.size();i++){
if(lists[i]){
q.push(lists[i]);
}
}
ListNode *temp=NULL;
ListNode *pre=NULL;
ListNode *head=NULL;
while(!q.empty()){
temp=q.top();
q.pop();
if(!pre){
head=temp;
}else{
pre->next=temp;
}
pre=temp;
if(temp->next){
q.push(temp->next);
}
}
return head;
}
};
参考文献
[LeetCode] Merge k Sorted Lists 合并k个有序链表
23. Merge k Sorted Lists
priority_queue的用法
1208




被折叠的 条评论
为什么被折叠?



