File tree Expand file tree Collapse file tree 1 file changed +25
-27
lines changed
0023-merge-k-sorted-lists Expand file tree Collapse file tree 1 file changed +25
-27
lines changed Original file line number Diff line number Diff line change 8
8
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9
9
* }
10
10
*/
11
- public class Solution {
12
- public static ListNode mergeKLists (ListNode [] lists ){
13
- return partion (lists ,0 ,lists .length -1 );
14
- }
15
-
16
- public static ListNode partion (ListNode [] lists ,int s ,int e ){
17
- if (s ==e ) return lists [s ];
18
- if (s <e ){
19
- int q =(s +e )/2 ;
20
- ListNode l1 =partion (lists ,s ,q );
21
- ListNode l2 =partion (lists ,q +1 ,e );
22
- return merge (l1 ,l2 );
23
- }else
24
- return null ;
25
- }
26
-
27
- //This function is from Merge Two Sorted Lists.
28
- public static ListNode merge (ListNode l1 ,ListNode l2 ){
29
- if (l1 ==null ) return l2 ;
30
- if (l2 ==null ) return l1 ;
31
- if (l1 .val <l2 .val ){
32
- l1 .next =merge (l1 .next ,l2 );
33
- return l1 ;
34
- }else {
35
- l2 .next =merge (l1 ,l2 .next );
36
- return l2 ;
11
+ class Solution {
12
+ public ListNode mergeKLists (ListNode [] lists ) {
13
+ PriorityQueue <ListNode > minheap = new PriorityQueue <ListNode >((a ,b )->(a .val -b .val ));
14
+ for (ListNode list :lists ){
15
+ if (list !=null )
16
+ minheap .add (list );
17
+ }
18
+ ListNode head =null ;
19
+ ListNode tail =null ;
20
+ while (!minheap .isEmpty ()){
21
+ ListNode p =minheap .poll ();
22
+ if (head ==null ){
23
+ head =p ;
24
+ tail =p ;
25
+ }else {
26
+ tail .next =p ;
27
+ tail =p ;
28
+ }
29
+ if (p .next !=null ){
30
+ minheap .add (p .next );
31
+ }
32
+ }
33
+ return head ;
34
+
37
35
}
38
- }
36
+
39
37
}
You can’t perform that action at this time.
0 commit comments