-
-
Notifications
You must be signed in to change notification settings - Fork 8.7k
/
Copy pathSolution.cs
32 lines (32 loc) · 909 Bytes
/
Solution.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode MergeKLists(ListNode[] lists) {
PriorityQueue<ListNode, int> pq = new PriorityQueue<ListNode, int>();
foreach (var head in lists) {
if (head != null) {
pq.Enqueue(head, head.val);
}
}
var dummy = new ListNode();
var cur = dummy;
while (pq.Count > 0) {
var node = pq.Dequeue();
cur.next = node;
cur = cur.next;
if (node.next != null) {
pq.Enqueue(node.next, node.next.val);
}
}
return dummy.next;
}
}