Crack LeetCode 之 23. Merge k Sorted Lists
阿新 • • 發佈:2018-12-16
本題有兩種解法,一是採用之前歸併排序裡面的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; } };