Skip to content

Commit 4878513

Browse files
committed
Time: 4 ms (75.52%), Space: 44.5 MB (40.37%) - LeetHub
1 parent 56fcf8b commit 4878513

File tree

1 file changed

+25
-27
lines changed

1 file changed

+25
-27
lines changed

0023-merge-k-sorted-lists/0023-merge-k-sorted-lists.java

Lines changed: 25 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -8,32 +8,30 @@
88
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
99
* }
1010
*/
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+
3735
}
38-
}
36+
3937
}

0 commit comments

Comments
 (0)