[关闭]
@snuffles 2019-04-10T23:46:47.000000Z 字数 1025 阅读 898

L23 合并K个有序链表

链表


合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6

解1:分治法,对半划分,如果有6个链表,合并0,3;1,4;2,5(n+1)/2;
解2:最小堆

  1. //最小堆
  2. ListNode* mergeKLists(vector<ListNode*>& lists) {
  3. auto cmp=[](ListNode * &a, ListNode*&b){
  4. return a->val > b->val;
  5. };
  6. priority_queue<ListNode*,vector<ListNode*>,decltype(cmp) > q(cmp);
  7. for(auto node:lists){
  8. if(node) q.push(node);
  9. }
  10. ListNode *dummy = new ListNode(-1),*cur=dummy;
  11. while(!q.empty()){
  12. auto t = q.top();
  13. q.pop();
  14. cur->next = t;
  15. cur = cur->next;
  16. if(cur->next) q.push(cur->next);
  17. }
  18. return dummy->next;
  19. }
  1. ListNode* mergeKLists(vector<ListNode*>& lists) {
  2. vector<int> nums;
  3. if (lists.size()==0) return NULL;
  4. if (lists.size()==1) return lists[0];
  5. ListNode *cur = lists[0];
  6. for(int i=0;i<lists.size();i++){
  7. // head
  8. cur = lists[i];
  9. // give all num
  10. while(cur!=NULL){
  11. nums.push_back(cur->val);
  12. cur = cur->next;
  13. }
  14. }
  15. cout << nums.size() << endl;
  16. if(nums.empty()) return NULL;
  17. sort(nums.begin(),nums.end());
  18. ListNode *newhead = new ListNode(nums[0]);
  19. cur = newhead;
  20. for(int i=1;i<nums.size();i++){
  21. cur->next = new ListNode(nums[i]);
  22. cur = cur->next;
  23. }
  24. cur->next =NULL;
  25. return newhead;
  26. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注