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

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode mergeKLists(List<ListNode> lists) {
14         ListNode head=new ListNode(-1);
15         ListNode tail=head;
16         if(lists.size()<=0) return null;
17         Comparator<ListNode> mycmp=new Comparator<ListNode>()
18         {
19             public int compare(ListNode l1,ListNode l2)
20             {
21                 if(l1.val>l2.val) return 1;
22                 else if(l1.val<l2.val)return -1;
23                 return 0;
24                 
25                 
26                 
27             }
28             
29         } ;
30         
31         PriorityQueue<ListNode> prq=new PriorityQueue<ListNode>(lists.size(),mycmp);
32         for(ListNode n:lists)
33         {
34             if(n!=null)
35             {
36                 prq.add(n);
37             }
38             
39         }
40         while(prq.size()>0)
41         {
42             ListNode tem=prq.poll();
43             tail.next=tem;
44             tail=tail.next;
45             if(tem.next!=null)
46             {
47                 prq.add(tem.next);
48             }
49     
50             
51         }
52         
53             return head.next;
54         
55         
56         
57         
58         
59     }
60 }
View Code
原文地址:https://www.cnblogs.com/hansongjiang/p/3847638.html