https://leetcode.com/problems/merge-k-sorted-lists/
本题有两种解法,一是采用之前归并排序里面的merge函数把链表两辆合并;二是采用堆算法,具体参考这个链接:
https://blog.csdn.net/linhuanmars/article/details/19899259
解法一的时间复杂度是O(n log(n)),空间复杂度是O(1);解法二的时间复杂度是O(n log(n)),空间复杂度也是O(1)。Python的优先级队列使用比较麻烦,所以没有在这里列出Python的解法二。
C++的解法一:
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty())
return NULL;
return _mergeKLists(lists,0,lists.size()-1);
}
ListNode * _mergeKLists(vector<ListNode*>& lists, int l, int r) {
if( l < r )
return merge(_mergeKLists(lists,l,(l+r) / 2),_mergeKLists(lists,(l+r) / 2+1,r));
return lists[l];
}
ListNode * merge(ListNode * head1, ListNode * head2) {
ListNode * helper = new ListNode(0);
helper->next = head1;
ListNode * pre = helper;
while(head1!=NULL && head2!=NULL) {
if(head1->val<head2->val)
head1 = head1->next;
else {
ListNode * next = head2->next;
head2->next = head1;
pre->next = head2;
head2 = next;
}
pre = pre->next;
}
if(head2!=NULL)
pre->next = head2;
return helper->next;
}
};
Python的解法一:
class Solution:
def mergeKLists(self, lists):
if lists == None or len(lists) == 0:
return None
return self._mergeKLists(lists, 0, len(lists)-1)
def _mergeKLists(self, lists, l, r):
if l >= r:
return lists[l]
return self.merge(self._mergeKLists(lists, l, int((l+r)/2)), self._mergeKLists(lists, int((l+r)/2)+1, r))
def merge(self, l1, l2):
if l1 == None:
return l2
if l2 == None:
return l1
head = ListNode(0)
head.next = l1
pre = head
while l1 != None and l2 != None:
if l1.val < l2.val:
l1 = l1.next
else:
next = l2.next
l2.next = l1
pre.next = l2
l2 = next
pre = pre.next
if l2 != None:
pre.next = l2
return head.next
C++的解法二:
struct Solution {
bool operator() (ListNode *& lhs, ListNode *& rhs) { return (lhs->val > rhs->val ? true : false); }
ListNode* mergeKLists(vector<ListNode*>& lists) {
std::priority_queue<ListNode*, std::vector<ListNode*>, Solution> heap;
for(int i=0; i<lists.size(); ++i) {
if(lists[i])
heap.push(lists[i]);
}
ListNode * head = NULL;
ListNode * pre = NULL;
while(heap.empty() == false) {
ListNode * cur = heap.top();
heap.pop();
if(head)
pre->next = cur;
else
head = cur;
pre = cur;
if(cur->next)
heap.push(cur->next);
}
return head;
}
};