Merge k Sorted Lists
题目:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
题意:
合并k个已经排序过的链表。
思路:
1.一次合并两个,合并k-1次,但是超时了 Time Limit Exceeded,o(n^2)级别
2.类似归并排序o(nlogn)
3.利用堆性质。其实就是每次比较所有链表的对应的首节点,然后找到最小的,添加到新链表上,删除原链表的最小那个节点,接着让被删除节点的链表的下一个节点进来参与比较。我们使用堆能将时间复杂度降到nlogn级别,和刚刚说的一样,就是把所有链表的首节点建一个堆,然后在堆中删除最小值时间复杂度是log n。删除后在让下一个进堆。
代码:
思路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){
if(l1 == NULL && l2 == NULL){
return NULL;
}else if(l1 == NULL && l2 != NULL){
return l2;
}else if(l1 != NULL && l2 == NULL){
return l1;
}
ListNode *new_head = NULL;
if(l1->val < l2->val){
new_head = l1;
l1 = l1->next;
}else{
new_head = l2;
l2 = l2->next;
}
ListNode *p = new_head;
while(l1 != NULL && l2 != NULL){
if(l1->val < l2->val){
p->next = l1;
p = p->next;
l1 = l1->next;
}else{
p->next = l2;
p = p->next;
l2 = l2->next;
}
}
if(l1 != NULL){
p->next = l1;
}else if(l2 != NULL){
p->next = l2;
}
return new_head;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() == 0){
return NULL;
}else if(lists.size() == 1){
return lists[0];
}
ListNode *ret;
for(int i = lists.size()-1; i > 0; --i){
ret = mergeTwoLists(lists[i], lists[i-1]);
lists[i-1] = ret;
}
return lists[0];
}
};
思路2:(通过)
/**
* 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){
if(l1 == NULL && l2 == NULL){
return NULL;
}else if(l1 == NULL && l2 != NULL){
return l2;
}else if(l1 != NULL && l2 == NULL){
return l1;
}
ListNode *new_head = NULL;
if(l1->val < l2->val){
new_head = l1;
l1 = l1->next;
}else{
new_head = l2;
l2 = l2->next;
}
ListNode *p = new_head;
while(l1 != NULL && l2 != NULL){
if(l1->val < l2->val){
p->next = l1;
p = p->next;
l1 = l1->next;
}else{
p->next = l2;
p = p->next;
l2 = l2->next;
}
}
if(l1 != NULL){
p->next = l1;
}else if(l2 != NULL){
p->next = l2;
}
return new_head;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() == 0){
return NULL;
}else if(lists.size() == 1){
return lists[0];
}
auto length = lists.end()-lists.begin();
auto mid = lists.begin() + (length-1)/2;
vector<ListNode*>v1(lists.begin(), mid+1);
vector<ListNode*>v2(mid+1, lists.end());
//归并排序的思想
ListNode *l1 = mergeKLists(v1);
ListNode *l2 = mergeKLists(v2);
return mergeTwoLists(l1, l2);
}
};