Skip to content

Commit 00363b0

Browse files
committed
solve merge k sorted list
1 parent 9083b8b commit 00363b0

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

merge-k-sorted-lists/sora0319.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
public class Solution {
2+
public ListNode mergeKLists(ListNode[] lists) {
3+
PriorityQueue<ListNode> pq = new PriorityQueue<>(Comparator.comparingInt(node -> node.val));
4+
5+
for (ListNode list : lists) {
6+
if (list != null) {
7+
pq.offer(list);
8+
}
9+
}
10+
11+
ListNode temp = new ListNode(-1);
12+
ListNode head = temp;
13+
14+
while (!pq.isEmpty()) {
15+
ListNode minNode = pq.poll();
16+
head.next = minNode;
17+
head = head.next;
18+
19+
if (minNode.next != null) {
20+
pq.offer(minNode.next);
21+
}
22+
}
23+
24+
return temp.next;
25+
}
26+
}

0 commit comments

Comments
 (0)