Merge k Sorted Lists

描述

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

分析

可以复用 Merge Two Sorted Lists 的函数

代码

  1. // Merge k Sorted Lists
  2. // 时间复杂度O(n1+n2+...),空间复杂度O(1)
  3. // TODO: 会超时
  4. class Solution {
  5. public:
  6. ListNode *mergeKLists(vector &lists) {
  7. if (lists.size() == 0) return nullptr;
  8. ListNode *p = lists[0];
  9. for (int i = 1; i < lists.size(); i++) {
  10. p = mergeTwoLists(p, lists[i]);
  11. }
  12. return p;
  13. }
  14. // Merge Two Sorted Lists
  15. ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
  16. ListNode head(-1);
  17. for (ListNode* p = &head; l1 != nullptr || l2 != nullptr; p = p->next) {
  18. int val1 = l1 == nullptr ? INT_MAX : l1->val;
  19. int val2 = l2 == nullptr ? INT_MAX : l2->val;
  20. if (val1 next = l1;
  21. l1 = l1->next;
  22. } else {
  23. p->next = l2;
  24. l2 = l2->next;
  25. }
  26. }
  27. return head.next;
  28. }
  29. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/sorting/merge-sort/merge-k-sorted-lists.html