Skip to content

Commit c413dad

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 23_Merge_k_Sorted_Lists.java
1 parent 6fdb734 commit c413dad

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

K-way Merge/.gitkeep

Whitespace-only changes.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public ListNode mergeKLists(ListNode[] lists) {
3+
if (lists == null || lists.length == 0) {
4+
return null;
5+
}
6+
7+
ListNode dummy = new ListNode(-1);
8+
ListNode curr = dummy;
9+
10+
PriorityQueue<ListNode> pq = new PriorityQueue<>((l1, l2) -> l1.val - l2.val);
11+
12+
for (ListNode ln : lists) {
13+
if (ln != null) {
14+
pq.offer(ln);
15+
}
16+
}
17+
18+
while (!pq.isEmpty()) {
19+
ListNode l = pq.poll();
20+
21+
if (l.next != null) {
22+
pq.offer(l.next);
23+
}
24+
25+
curr.next = l;
26+
curr = curr.next;
27+
}
28+
29+
return dummy.next;
30+
}
31+
}

0 commit comments

Comments
 (0)