-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1c60fed
commit 19c3560
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
// TC: O(n * log m) | ||
// m -> the number of the lists, n -> the number of node | ||
// SC: O(m) | ||
// m -> the number of the lists (max m) | ||
class Solution { | ||
public ListNode mergeKLists(ListNode[] lists) { | ||
if (lists == null || lists.length == 0) return null; | ||
|
||
PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val); | ||
|
||
for (ListNode node : lists) { | ||
if (node != null) pq.offer(node); | ||
} | ||
|
||
ListNode dummy = new ListNode(0); | ||
ListNode current = dummy; | ||
|
||
while (!pq.isEmpty()) { | ||
ListNode minNode = pq.poll(); | ||
current.next = minNode; | ||
current = current.next; | ||
|
||
if (minNode.next != null) { | ||
pq.offer(minNode.next); | ||
} | ||
} | ||
|
||
return dummy.next; | ||
} | ||
} |