合并k个有序链表

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

 1     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
 2         if (l1 == null) {
 3             return l2 ;
 4         }
 5         if (l2 == null) {
 6             return l1;
 7         }
 8         ListNode dummy = new ListNode(-1);
 9         ListNode pre = dummy;
10         while (l1 != null && l2 != null) {
11             if (l1.val < l2.val) {
12                 pre.next = l1;
13                 l1 = l1.next;
14             } else {
15                 pre.next = l2;
16                 l2 = l2.next;
17             }
18             pre = pre.next;
19         }
20         while (l1 != null) {
21             pre.next = l1;
22         }
23         while (l2 != null) {
24             pre.next = l2;
25         }
26         return dummy.next;
27     }

 

合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

示例:

输入:
[
  1->4->5,
  1->3->4,
  2->6
]
输出: 1->1->2->3->4->4->5->6

 1 public class T23 {
 2     public ListNode mergeKLists(ListNode[] lists) {
 3         ListNode dummy = new ListNode(-1);
 4         ListNode pre = dummy;
 5         if (lists == null || lists.length == 0) {
 6             return dummy.next;
 7         }
 8         PriorityQueue<ListNode> que = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
 9             @Override
10             public int compare(ListNode o1, ListNode o2) {
11                 return o1.val - o2.val;
12             }
13         });
14         for (ListNode node : lists) {
15             if (node != null) {
16                 que.add(node);
17             }
18         }
19 
20         while (!que.isEmpty()) {
21             pre.next = que.poll();
22             pre = pre.next;
23             if (pre.next != null) {
24                 que.add(pre.next);
25             }
26         }
27         return dummy.next;
28     }
29 }

 弹出时,比较的操作是log(k),k为链表的数目,取得最小点的操作时间是O(1)。一共有n个点。故时间复杂度是O(nlog(k))。

posted @ 2020-03-16 18:06  海绵爱上星  阅读(591)  评论(0编辑  收藏  举报