Day3. Start Algorithm

This commit is contained in:
Electrominch
2022-10-05 00:44:15 +03:00
parent c9916dabad
commit 062e03bdbf
32 changed files with 446 additions and 57 deletions

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_21._Merge_Two_Sorted_Lists</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,37 @@
namespace _21._Merge_Two_Sorted_Lists;
//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 static ListNode Create(int[] nums)
{
ListNode l = new ListNode(nums[0]);
ListNode cur = l;
for (int i = 1; i < nums.Length; i++)
{
cur.next = new ListNode(nums[i]);
cur = cur.next;
}
return l;
}
public override string ToString()
{
List<int> list = new List<int>();
ListNode? cur = this;
while (cur != null)
{
list.Add(cur.val);
cur = cur.next;
}
return String.Join(" ", list);
}
}

View File

@@ -0,0 +1,12 @@
namespace _21._Merge_Two_Sorted_Lists
{
internal class Program
{
static void Main(string[] args)
{
var l1 = ListNode.Create(new int[] { 1, 2, 4 });
var l2 = ListNode.Create(new int[] { 1, 3, 4 });
Console.WriteLine(new Solution().MergeTwoLists(l1, l2));
}
}
}

View File

@@ -0,0 +1,44 @@
namespace _21._Merge_Two_Sorted_Lists;
public class Solution
{
public ListNode MergeTwoLists(ListNode? list1, ListNode? list2)
{
ListNode? start = null;
ListNode? current = null;
List<ListNode?> listNodes = new List<ListNode?>() { list1, list2 };
while (listNodes.Any(l => l != null))
{
int i = MinIndex(listNodes);
ListNode? curMin = listNodes[i];
listNodes[i] = listNodes[i]!.next;
if (start == null)
{
start = curMin;
current = start;
}
else if (current != null)
{
current.next = curMin;
current = current.next;
}
}
return start!;
}
private int MinIndex(List<ListNode?> list)
{
int minValue = int.MaxValue;
int index = -1;
for (int i = 0; i < list.Count; i++)
{
if (list[i]?.val < minValue)
{
minValue = list[i]!.val;
index = i;
}
}
return index;
}
}