-
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
eunhwa99
committed
Feb 14, 2025
1 parent
441e43a
commit f357000
Showing
1 changed file
with
35 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,35 @@ | ||
import java.util.PriorityQueue; | ||
|
||
/** | ||
* Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode() {} | ||
* ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; | ||
* this.next = next; } } | ||
*/ | ||
|
||
// TC : PQ -> O(NlogN) | ||
// SC: Linked list -> O(N) | ||
class Solution { | ||
|
||
public ListNode mergeKLists(ListNode[] lists) { | ||
if (lists == null || lists.length == 0) { | ||
return null; | ||
} | ||
PriorityQueue<Integer> pq = new PriorityQueue<>(); | ||
|
||
for (int i = 0; i < lists.length; i++) { | ||
while (lists[i] != null) { | ||
pq.add(lists[i].val); | ||
lists[i] = lists[i].next; | ||
} | ||
} | ||
ListNode dummy = new ListNode(0); | ||
ListNode current = dummy; | ||
while (!pq.isEmpty()) { | ||
current.next = new ListNode(pq.poll()); | ||
current = current.next; | ||
} | ||
|
||
return dummy.next; | ||
} | ||
} | ||
|