题意:

image.png

解题思路:

  1. 思路:
  2. 1. 分治合并;O(nlogk) //同21.合并两个有序链表 相关联
  3. 2. 小顶堆;每次O(logK),比较K个指针求min, 时间复杂度:O(NlogK)

PHP代码实现:

  1. /**
  2. * Definition for a singly-linked list.
  3. * class ListNode {
  4. * public $val = 0;
  5. * public $next = null;
  6. * function __construct($val) { $this->val = $val; }
  7. * }
  8. */
  9. class Solution {
  10. /**
  11. * @param ListNode[] $lists
  12. * @return ListNode
  13. */
  14. function mergeKLists($lists) {
  15. $left = 0; $right = count($lists);
  16. return $this->merge($lists, $left, $right);
  17. }
  18. function merge($list, $left, $right) {
  19. if ($left >= $right) return $list[$left];
  20. $mid = $left + floor(($right - $left) >> 1);
  21. $l1 = $this->merge($list, $left, $mid);
  22. $l2 = $this->merge($list, $mid + 1, $right);
  23. return $this->mergeTwoSortedLists($l1, $l2);
  24. }
  25. function mergeTwoSortedLists($l1, $l2) {
  26. $dummy = new ListNode(0);
  27. $cur = $dummy;
  28. while ($l1 != null && $l2 != null) {
  29. if ($l1->val <= $l2->val) {
  30. $cur->next = $l1;
  31. $l1 = $l1->next;
  32. } else {
  33. $cur->next = $l2;
  34. $l2 = $l2->next;
  35. }
  36. $cur = $cur->next;
  37. }
  38. $cur->next = $l1 == null ? $l2 : $l1;
  39. return $dummy->next;
  40. }
  41. //小顶堆
  42. function mergeKLists($lists) {
  43. if (count($lists) == 0) return;
  44. $dummy = new ListNode(0);
  45. $cur = $dummy;
  46. $minHeap = new SplMinHeap;
  47. foreach ($lists as $l) $minHeap->insert($l);
  48. while (!$minHeap->isEmpty()) {
  49. $l = $minHeap->top();
  50. $minHeap->next();
  51. if ($l->next != null) $minHeap->insert($l->next);
  52. if ($l) {
  53. $cur->next = $l;
  54. $cur = $cur->next;
  55. }
  56. }
  57. return $dummy->next;
  58. }
  59. }

GO代码实现:

  1. /**
  2. * Definition for singly-linked list.
  3. * type ListNode struct {
  4. * Val int
  5. * Next *ListNode
  6. * }
  7. */
  8. func mergeKLists(lists []*ListNode) *ListNode {
  9. if 0 == len(lists) { return nil }
  10. return merge(lists, 0, len(lists) - 1)
  11. }
  12. func merge(lists []*ListNode, left, right int) *ListNode {
  13. if left == right {
  14. return lists[left]
  15. }
  16. mid := left + (right - left) / 2
  17. l1 := merge(lists, left, mid)
  18. l2 := merge(lists, mid+1, right)
  19. return mergeTwoSortedLists(l1, l2)
  20. }
  21. func mergeTwoSortedLists(l1 *ListNode, l2 *ListNode) *ListNode {
  22. dummy := &ListNode{}
  23. cur := dummy
  24. for l1 != nil && l2 != nil {
  25. if l1.Val < l2.Val {
  26. cur.Next = l1
  27. l1 = l1.Next
  28. } else {
  29. cur.Next = l2
  30. l2 = l2.Next
  31. }
  32. cur = cur.Next
  33. }
  34. if l1 != nil {
  35. cur.Next = l1
  36. }
  37. if l2 != nil {
  38. cur.Next = l2
  39. }
  40. return dummy.Next
  41. }