Skip to content

Commit f357000

Browse files
author
eunhwa99
committed
merged k sorted lists
1 parent 441e43a commit f357000

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

merge-k-sorted-lists/eunhwa99.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.util.PriorityQueue;
2+
3+
/**
4+
* Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode() {}
5+
* ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val;
6+
* this.next = next; } }
7+
*/
8+
9+
// TC : PQ -> O(NlogN)
10+
// SC: Linked list -> O(N)
11+
class Solution {
12+
13+
public ListNode mergeKLists(ListNode[] lists) {
14+
if (lists == null || lists.length == 0) {
15+
return null;
16+
}
17+
PriorityQueue<Integer> pq = new PriorityQueue<>();
18+
19+
for (int i = 0; i < lists.length; i++) {
20+
while (lists[i] != null) {
21+
pq.add(lists[i].val);
22+
lists[i] = lists[i].next;
23+
}
24+
}
25+
ListNode dummy = new ListNode(0);
26+
ListNode current = dummy;
27+
while (!pq.isEmpty()) {
28+
current.next = new ListNode(pq.poll());
29+
current = current.next;
30+
}
31+
32+
return dummy.next;
33+
}
34+
}
35+

0 commit comments

Comments
 (0)