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. public class Solution {
  5. public ListNode mergeKLists(ListNode[] lists) {
  6. if (lists.length == 0) return null;
  7. ListNode p = lists[0];
  8. for (int i = 1; i < lists.length; i++) {
  9. p = mergeTwoLists(p, lists[i]);
  10. }
  11. return p;
  12. }
  13. // Merge Two Sorted Lists
  14. ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  15. ListNode head = new ListNode(-1);
  16. for (ListNode p = head; l1 != null || l2 != null; p = p.next) {
  17. int val1 = l1 == null ? Integer.MAX_VALUE : l1.val;
  18. int val2 = l2 == null ? Integer.MAX_VALUE : l2.val;
  19. if (val1

相关题目

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