Skip to content

Commit

Permalink
merged k sorted lists
Browse files Browse the repository at this point in the history
  • Loading branch information
eunhwa99 committed Feb 14, 2025
1 parent 441e43a commit f357000
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions merge-k-sorted-lists/eunhwa99.java
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;
}
}

0 comments on commit f357000

Please sign in to comment.