23. Merge k Sorted Lists
This commit is contained in:
11
23. Merge k Sorted Lists/23. Merge k Sorted Lists.csproj
Normal file
11
23. Merge k Sorted Lists/23. Merge k Sorted Lists.csproj
Normal file
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>_23._Merge_k_Sorted_Lists</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
11
23. Merge k Sorted Lists/ListNode.cs
Normal file
11
23. Merge k Sorted Lists/ListNode.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
|
||||
public class ListNode
|
||||
{
|
||||
public int val;
|
||||
public ListNode? next;
|
||||
public ListNode(int val = 0, ListNode? next = null)
|
||||
{
|
||||
this.val = val;
|
||||
this.next = next;
|
||||
}
|
||||
}
|
||||
2
23. Merge k Sorted Lists/Program.cs
Normal file
2
23. Merge k Sorted Lists/Program.cs
Normal file
@@ -0,0 +1,2 @@
|
||||
// See https://aka.ms/new-console-template for more information
|
||||
Console.WriteLine("Hello, World!");
|
||||
29
23. Merge k Sorted Lists/Solution.cs
Normal file
29
23. Merge k Sorted Lists/Solution.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
public class Solution
|
||||
{
|
||||
public ListNode? MergeKLists(ListNode[] lists)
|
||||
{
|
||||
ListNode? head = null;
|
||||
ListNode? tail = null;
|
||||
var queue = new PriorityQueue<ListNode, int>();
|
||||
foreach (var l in lists)
|
||||
if (l != null)
|
||||
queue.Enqueue(l, l.val);
|
||||
while (queue.Count > 0)
|
||||
{
|
||||
var l = queue.Dequeue();
|
||||
if (head == null || tail == null)
|
||||
{
|
||||
head = l;
|
||||
tail = l;
|
||||
}
|
||||
else
|
||||
{
|
||||
tail.next = l;
|
||||
tail = l;
|
||||
}
|
||||
if (l.next != null)
|
||||
queue.Enqueue(l.next, l.next.val);
|
||||
}
|
||||
return head;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user