Merge k Sorted Lists
题目详情:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
解题方法:
看到这个题目首先想到归并排序,但是这是一个链表的vector,要求返回一个链表,首先想到了先前两个进行合并,在把结果得到的链表在与后面的链表两两合并,但是说超出内存。后来利用vector的属性,实现了这种操作。
代码详情:
/**
* 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;
while(lists.size()>1) {
lists.push_back(merge(lists[0],lists[1]));
lists.erase(lists.begin());
lists.erase(lists.begin());
}
return lists[0];
}
ListNode *merge(ListNode *l1, ListNode *l2) {
if (l1 == NULL) {
return l2;
}
if (l2 == NULL) {
return l1;
}
if (l1->val <= l2->val) {
l1->next = merge(l1->next,l2);
return l1;
} else {
l2->next = merge(l1, l2->next);
return l2;
}
}
};
* 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;
while(lists.size()>1) {
lists.push_back(merge(lists[0],lists[1]));
lists.erase(lists.begin());
lists.erase(lists.begin());
}
return lists[0];
}
ListNode *merge(ListNode *l1, ListNode *l2) {
if (l1 == NULL) {
return l2;
}
if (l2 == NULL) {
return l1;
}
if (l1->val <= l2->val) {
l1->next = merge(l1->next,l2);
return l1;
} else {
l2->next = merge(l1, l2->next);
return l2;
}
}
};
复杂度分析:
merge部分最差情况下为2n-1,mergeKLists部分为logn,所以复杂度为nlogn