Compare commits

..

26 Commits

Author SHA1 Message Date
2cac465442 3548. Equal Sum Grid Partition II 2026-03-26 13:33:38 +03:00
3f3bc52106 Оптимально 2026-03-26 00:22:10 +03:00
4681660c8c 30. Substring with Concatenation of All Words 2026-03-25 23:58:01 +03:00
6b483ea6d1 114. Flatten Binary Tree to Linked List 2026-03-25 23:18:30 +03:00
a8727e17a1 32. Longest Valid Parentheses 2026-03-25 22:56:24 +03:00
8c963d3aa2 31. Next Permutation 2026-03-25 20:28:57 +03:00
48d637475f 26. Remove Duplicates from Sorted Array 2026-03-25 19:47:09 +03:00
12912123de 23. Merge k Sorted Lists 2026-03-25 17:32:12 +03:00
2464aeff0e 18. 4Sum 2026-03-25 16:58:20 +03:00
d99b7d18e3 3546. Equal Sum Grid Partition I 2026-03-25 12:43:02 +03:00
a3131bf6d0 2906. Construct Product Matrix 2026-03-25 11:50:01 +03:00
1e973f5a9e начало 2906 2026-03-24 22:29:36 +03:00
e6107b6dca медленное решение для 10. Regular Expression Matching 2026-03-24 01:04:03 +03:00
6c9412cc14 задача про палиндромы 2026-03-22 22:21:16 +03:00
ec73b7d661 начало задачи про палиндром 2026-03-22 15:53:38 +03:00
2e3f7b7776 nullable 2026-03-22 01:46:10 +03:00
5014a24cc8 dotnet 8.0 2026-03-22 01:41:46 +03:00
Пытков Роман
9b3c8c3fef 347. Top K Frequent Elements 2024-02-07 23:27:37 +03:00
Пытков Роман
c47d2185b5 fast solution 451 2024-02-07 22:08:26 +03:00
Пытков Роман
bfb8311fe7 451. Sort Characters By Frequency 2024-02-07 21:53:40 +03:00
Пытков Роман
d15aa071c8 9. Palindrome Number 2024-01-31 01:05:39 +03:00
Пытков Роман
9d50f345d1 150. Evaluate Reverse Polish Notation 2024-01-31 00:49:39 +03:00
Пытков Роман
1e43adf29e 14. Longest Common Prefix 2024-01-30 23:47:49 +03:00
Пытков Роман
66ea6b80f4 225. Implement Stack using Queues 2024-01-30 23:36:49 +03:00
Пытков Роман
8b40248caf Optimize 2024-01-30 23:19:36 +03:00
nullptroma
75d2db5b75 Two Tasks 2023-04-06 22:17:31 +03:00
158 changed files with 3099 additions and 506 deletions

View File

@@ -15,6 +15,7 @@
<projectFile>144. Binary Tree Preorder Traversal/144. Binary Tree Preorder Traversal.csproj</projectFile>
<projectFile>145. Binary Tree Postorder Traversal/145. Binary Tree Postorder Traversal.csproj</projectFile>
<projectFile>1480. Running Sum of 1d Array/1480. Running Sum of 1d Array.csproj</projectFile>
<projectFile>15. 3Sum/15. 3Sum.csproj</projectFile>
<projectFile>167. Two Sum II - Input Array Is Sorted/167. Two Sum II - Input Array Is Sorted.csproj</projectFile>
<projectFile>189. Rotate Array/189. Rotate Array.csproj</projectFile>
<projectFile>19. Remove Nth Node From End of List/19. Remove Nth Node From End of List.csproj</projectFile>
@@ -29,6 +30,7 @@
<projectFile>206. Reverse Linked List/206. Reverse Linked List.csproj</projectFile>
<projectFile>21. Merge Two Sorted Lists/21. Merge Two Sorted Lists.csproj</projectFile>
<projectFile>217. Contains Duplicate/217. Contains Duplicate.csproj</projectFile>
<projectFile>225. Implement Stack using Queues/225. Implement Stack using Queues.csproj</projectFile>
<projectFile>226. Invert Binary Tree/226. Invert Binary Tree.csproj</projectFile>
<projectFile>231. Power of Two/231. Power of Two.csproj</projectFile>
<projectFile>232. Implement Queue using Stacks/232. Implement Queue using Stacks.csproj</projectFile>
@@ -40,6 +42,7 @@
<projectFile>299. Bulls and Cows/299. Bulls and Cows.csproj</projectFile>
<projectFile>3. Longest Substring Without Repeating Characters/3. Longest Substring Without Repeating Characters.csproj</projectFile>
<projectFile>344. Reverse String/344. Reverse String.csproj</projectFile>
<projectFile>347. Top K Frequent Elements/347. Top K Frequent Elements.csproj</projectFile>
<projectFile>35. Search Insert Position/35. Search Insert Position.csproj</projectFile>
<projectFile>350. Intersection of Two Arrays II/350. Intersection of Two Arrays II.csproj</projectFile>
<projectFile>36. Valid Sudoku/36. Valid Sudoku.csproj</projectFile>
@@ -50,6 +53,7 @@
<projectFile>409. Longest Palindrome/409. Longest Palindrome.csproj</projectFile>
<projectFile>424. Longest Repeating Character Replacement/424. Longest Repeating Character Replacement.csproj</projectFile>
<projectFile>438. Find All Anagrams in a String/438. Find All Anagrams in a String.csproj</projectFile>
<projectFile>451. Sort Characters By Frequency/451. Sort Characters By Frequency.csproj</projectFile>
<projectFile>46. Permutations/46. Permutations.csproj</projectFile>
<projectFile>509. Fibonacci Number/509. Fibonacci Number.csproj</projectFile>
<projectFile>53. Maximum Subarray/53. Maximum Subarray.csproj</projectFile>
@@ -72,6 +76,7 @@
<projectFile>746. Min Cost Climbing Stairs/746. Min Cost Climbing Stairs.csproj</projectFile>
<projectFile>77. Combinations/77. Combinations.csproj</projectFile>
<projectFile>784. Letter Case Permutation/784. Letter Case Permutation.csproj</projectFile>
<projectFile>8. String to Integer (atoi)/8. String to Integer (atoi).csproj</projectFile>
<projectFile>83. Remove Duplicates from Sorted List/83. Remove Duplicates from Sorted List.csproj</projectFile>
<projectFile>876. Middle of the Linked List/876. Middle of the Linked List.csproj</projectFile>
<projectFile>88. Merge Sorted Array/88. Merge Sorted Array.csproj</projectFile>
@@ -80,8 +85,14 @@
<projectFile>98. Validate Binary Search Tree/98. Validate Binary Search Tree.csproj</projectFile>
<projectFile>994. Rotting Oranges/994. Rotting Oranges.csproj</projectFile>
</component>
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="11f2de1c-1ee5-4aa4-91e6-11975ebd421f" name="Changes" comment="">
<change afterPath="$PROJECT_DIR$/347. Top K Frequent Elements/347. Top K Frequent Elements.csproj" afterDir="false" />
<change afterPath="$PROJECT_DIR$/347. Top K Frequent Elements/Program.cs" afterDir="false" />
<change afterPath="$PROJECT_DIR$/347. Top K Frequent Elements/Solution.cs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/.idea.Leetcode/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/.idea.Leetcode/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Leetcode.sln" beforeDir="false" afterPath="$PROJECT_DIR$/Leetcode.sln" afterDir="false" />
</list>
@@ -90,32 +101,61 @@
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="HighlightingSettingsPerFile">
<setting file="file://$PROJECT_DIR$/14. Longest Common Prefix/Program.cs" root0="FORCE_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/14. Longest Common Prefix/Solution.cs" root0="FORCE_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/225. Implement Stack using Queues/MyStack.cs" root0="SKIP_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/225. Implement Stack using Queues/Program.cs" root0="SKIP_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/232. Implement Queue using Stacks/MyQueue.cs" root0="SKIP_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/232. Implement Queue using Stacks/Program.cs" root0="SKIP_HIGHLIGHTING" />
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectColorInfo">{
&quot;associatedIndex&quot;: 3
}</component>
<component name="ProjectId" id="2MbItycivFzycjT9hquXZe9USRT" />
<component name="ProjectLevelVcsManager">
<ConfirmationsSetting value="2" id="Add" />
</component>
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
".NET Project.14. Longest Common Prefix.executor": "Run",
".NET Project.150. Evaluate Reverse Polish Notation.executor": "Run",
".NET Project.347. Top K Frequent Elements.executor": "Run",
".NET Project.451. Sort Characters By Frequency.executor": "Run",
".NET Project.9. Palindrome Number.executor": "Run",
"ASKED_ADD_EXTERNAL_FILES": "true",
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"WebServerToolWindowFactoryState": "false",
"last_opened_file_path": "/home/nullptr/Projects/dotNET/Leetcode/6. Zigzag Conversion/6. Zigzag Conversion.csproj",
"git-widget-placeholder": "main",
"last_opened_file_path": "/home/nullptr/Projects/dotnet/Leetcode/15. 3Sum/15. 3Sum.csproj",
"node.js.detected.package.eslint": "true",
"node.js.detected.package.tslint": "true",
"node.js.selected.package.eslint": "(autodetect)",
"node.js.selected.package.tslint": "(autodetect)",
"nodejs_package_manager_path": "npm",
"settings.editor.selected.configurable": "SolutionBuilderGeneralOptionsPage",
"vue.rearranger.settings.migration": "true"
},
"keyToStringList": {
"rider.external.source.directories": [
"/home/nullptr/.config/JetBrains/Rider2022.3/resharper-host/DecompilerCache",
"/home/nullptr/.config/JetBrains/Rider2022.3/resharper-host/SourcesCache",
"/home/nullptr/.config/JetBrains/Rider2023.3/resharper-host/DecompilerCache",
"/home/nullptr/.config/JetBrains/Rider2023.3/resharper-host/SourcesCache",
"/home/nullptr/.local/share/Symbols/src"
]
}
}]]></component>
<component name="RunManager" selected=".NET Project.6. Zigzag Conversion">
<component name="RunManager" selected=".NET Project.347. Top K Frequent Elements">
<configuration name="101. Symmetric Tree" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
@@ -350,6 +390,60 @@
<option name="Build" />
</method>
</configuration>
<configuration name="14. Longest Common Prefix" type="DotNetProject" factoryName=".NET Project" temporary="true">
<option name="EXE_PATH" value="$PROJECT_DIR$/14. Longest Common Prefix/bin/Debug/net8.0/14. Longest Common Prefix" />
<option name="PROGRAM_PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/14. Longest Common Prefix/bin/Debug/net8.0" />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/14. Longest Common Prefix/14. Longest Common Prefix.csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="1" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value="net8.0" />
<method v="2">
<option name="Build" />
</method>
</configuration>
<configuration name="150. Evaluate Reverse Polish Notation" type="DotNetProject" factoryName=".NET Project" temporary="true">
<option name="EXE_PATH" value="$PROJECT_DIR$/150. Evaluate Reverse Polish Notation/bin/Debug/net8.0/150. Evaluate Reverse Polish Notation" />
<option name="PROGRAM_PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/150. Evaluate Reverse Polish Notation/bin/Debug/net8.0" />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/150. Evaluate Reverse Polish Notation/150. Evaluate Reverse Polish Notation.csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="1" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value="net8.0" />
<method v="2">
<option name="Build" />
</method>
</configuration>
<configuration name="15. 3Sum" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/15. 3Sum/15. 3Sum.csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="1" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value="" />
<method v="2">
<option name="Build" />
</method>
</configuration>
<configuration name="167. Two Sum II - Input Array Is Sorted" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
@@ -602,6 +696,24 @@
<option name="Build" />
</method>
</configuration>
<configuration name="225. Implement Stack using Queues" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/225. Implement Stack using Queues/225. Implement Stack using Queues.csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="1" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value="" />
<method v="2">
<option name="Build" />
</method>
</configuration>
<configuration name="226. Invert Binary Tree" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
@@ -800,6 +912,24 @@
<option name="Build" />
</method>
</configuration>
<configuration name="347. Top K Frequent Elements" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/347. Top K Frequent Elements/347. Top K Frequent Elements.csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="1" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value="" />
<method v="2">
<option name="Build" />
</method>
</configuration>
<configuration name="350. Intersection of Two Arrays II" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
@@ -980,6 +1110,24 @@
<option name="Build" />
</method>
</configuration>
<configuration name="451. Sort Characters By Frequency" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/451. Sort Characters By Frequency/451. Sort Characters By Frequency.csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="1" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value="" />
<method v="2">
<option name="Build" />
</method>
</configuration>
<configuration name="46. Permutations" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
@@ -1448,6 +1596,24 @@
<option name="Build" />
</method>
</configuration>
<configuration name="8. String to Integer (atoi)" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/8. String to Integer (atoi)/8. String to Integer (atoi).csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="1" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value="" />
<method v="2">
<option name="Build" />
</method>
</configuration>
<configuration name="94. Binary Tree Inorder Traversal" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
@@ -1520,6 +1686,31 @@
<option name="Build" />
</method>
</configuration>
<configuration name="9. Palindrome Number" type="DotNetProject" factoryName=".NET Project" temporary="true">
<option name="EXE_PATH" value="$PROJECT_DIR$/9. Palindrome Number/bin/Debug/net8.0/9. Palindrome Number" />
<option name="PROGRAM_PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/9. Palindrome Number/bin/Debug/net8.0" />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/9. Palindrome Number/9. Palindrome Number.csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="1" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value="net8.0" />
<method v="2">
<option name="Build" />
</method>
</configuration>
<recent_temporary>
<list>
<item itemvalue=".NET Project.9. Palindrome Number" />
<item itemvalue=".NET Project.150. Evaluate Reverse Polish Notation" />
<item itemvalue=".NET Project.14. Longest Common Prefix" />
</list>
</recent_temporary>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
@@ -1530,6 +1721,9 @@
<option name="presentableId" value="Default" />
<updated>1678030074860</updated>
<workItem from="1678030078340" duration="114000" />
<workItem from="1680804946367" duration="3697000" />
<workItem from="1706644472303" duration="7903000" />
<workItem from="1707331420927" duration="3074000" />
</task>
<servers />
</component>
@@ -1538,6 +1732,7 @@
</component>
<component name="UnityUnitTestConfiguration" currentTestLauncher="NUnit" />
<component name="VcsManagerConfiguration">
<option name="ADD_EXTERNAL_FILES_SILENTLY" value="true" />
<option name="CLEAR_INITIAL_COMMIT_MESSAGE" value="true" />
</component>
</project>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_1._Two_Sum</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

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

View File

@@ -0,0 +1,29 @@
var solution = new Solution();
var examples = new (string s, string p, bool expected)[]
{
("aa", "a", false),
("aa", "a*", true),
("ab", ".*", true),
("aab", "c*a*b", true),
("mississippi", "mis*is*p*.", false),
("mississippi", "mis*is*ip*.", true),
("aaa", "a*a", true),
("aaa", "ab*a*c*a", true),
("ab", ".*c", false),
("", "c*", true),
("abcd", "d*", false),
("", "", true),
("a", ".", true),
("", "a*", true),
("aa", "b*a*", true),
("a", "ab*", true),
("abcaaaaaaabaabcabac", ".*ab.a.*a*a*.*b*b*", true),
("", "a*b*", true),
};
foreach (var example in examples)
{
var result = solution.IsMatch(example.s, example.p);
Console.WriteLine($"s = \"{example.s}\", p = \"{example.p}\" => {result} (expected {example.expected})");
}

View File

@@ -0,0 +1,59 @@
public class Solution
{
public bool IsMatch(string s, string p) => IsMatch(null, s, p);
private bool IsMatch(char? prev, ReadOnlySpan<char> str, ReadOnlySpan<char> pattern)
{
if (pattern.Length == 0 && str.Length == 0)
return true;
if (str.Length == 0)
{
if (CanBeEmpty(pattern))
return true;
return false;
}
if (pattern.Length == 0)
return false;
var sym = str[0];
var p = pattern[0];
// раскрытая звёздочка
var pSymOrDot = p == '*' ? prev : p; // превращаем звёздочку в символ или точку
// ожидаемый текущий символ, конкретный
var pSym = pSymOrDot == '.' ? sym : pSymOrDot;
// следующий символ *
if (pattern.Length > 1 && pattern[1] == '*')
{
var match = false;
var i = 0;
do
{
match |= IsMatch(i > 0 ? p : prev, str[i..], pattern[2..]);
if (match || i == str.Length || str[i] != p && p != '.')
break;
i++;
}
while (i <= str.Length);
return match;
}
else if (sym != pSym)
{
return false;
}
else
{
return IsMatch(pSymOrDot, str[1..], pattern[1..]);
}
}
private bool CanBeEmpty(ReadOnlySpan<char> pattern)
{
if (pattern.Length % 2 == 1)
return false;
for (var i = 1; i < pattern.Length; i += 2)
if (pattern[i] != '*')
return false;
return true;
}
}

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_101._Symmetric_Tree</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_102._Binary_Tree_Level_Order_Traversal</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_104._Maximum_Depth_of_Binary_Tree</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_112._Path_Sum</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

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

View File

@@ -0,0 +1,67 @@
var sol = new Solution();
var cases = new (int?[] input, int?[] expected)[]
{
(new int?[] { 1, 2, 5, 3, 4, null, 6 }, new int?[] { 1, null, 2, null, 3, null, 4, null, 5, null, 6 }),
// (Array.Empty<int?>(), Array.Empty<int?>()),
// (new int?[] { 0 }, new int?[] { 0 })
};
foreach (var (input, expected) in cases)
{
var root = BuildTreeFromLevelOrder(input);
if (root != null)
sol.Flatten(root);
var actual = FlattenToOutputList(root);
Console.WriteLine($"[{string.Join(", ", input.Select(FormatNullable))}] -> [{string.Join(", ", actual.Select(FormatNullable))}] (expected: [{string.Join(", ", expected.Select(FormatNullable))}])");
}
static TreeNode? BuildTreeFromLevelOrder(int?[] data)
{
if (data.Length == 0 || data[0] == null)
return null;
var root = new TreeNode(data[0]!.Value);
var queue = new Queue<TreeNode>();
queue.Enqueue(root);
var i = 1;
while (queue.Count > 0 && i < data.Length)
{
var node = queue.Dequeue();
if (i < data.Length && data[i] != null)
{
node.left = new TreeNode(data[i]!.Value);
queue.Enqueue(node.left);
}
i++;
if (i < data.Length && data[i] != null)
{
node.right = new TreeNode(data[i]!.Value);
queue.Enqueue(node.right);
}
i++;
}
return root;
}
static List<int?> FlattenToOutputList(TreeNode? root)
{
var result = new List<int?>();
var node = root;
while (node != null)
{
result.Add(node.val);
if (node.right != null)
result.Add(null);
node = node.right;
}
return result;
}
static string FormatNullable(int? value) => value?.ToString() ?? "null";

View File

@@ -0,0 +1,27 @@
public class Solution
{
public void Flatten(TreeNode? root)
{
if (root == null)
return;
var head = root;
var stack = new Stack<TreeNode>();
if (root.right != null)
stack.Push(root.right);
if (root.left != null)
stack.Push(root.left);
while (stack.Count > 0)
{
var node = stack.Pop();
head.left = null;
head.right = node;
head = node;
if (node.right != null)
stack.Push(node.right);
if (node.left != null)
stack.Push(node.left);
}
}
}

View File

@@ -0,0 +1,12 @@
public class TreeNode
{
public int val;
public TreeNode? left;
public TreeNode? right;
public TreeNode(int val = 0, TreeNode? left = null, TreeNode? right = null)
{
this.val = val;
this.left = left;
this.right = right;
}
}

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_116._Populating_Next_Right_Pointers_in_Each_Node</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_118._Pascal_s_Triangle</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_121._Best_Time_to_Buy_and_Sell_Stock</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_136._Single_Number</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

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

View File

@@ -0,0 +1,6 @@
// See https://aka.ms/new-console-template for more information
using _14._Longest_Common_Prefix;
string[] strs = ["flower", "flow", "flight"];
Console.WriteLine(new Solution().LongestCommonPrefix(strs));

View File

@@ -0,0 +1,32 @@
using System.Text;
namespace _14._Longest_Common_Prefix;
public class Solution
{
public string LongestCommonPrefix(string[] strs)
{
if (strs.Length == 1)
return strs[0];
StringBuilder sb = new StringBuilder(256);
int maxLen = strs.Select(s => s.Length).Min();
for (int i = 0; i < maxLen; i++)
{
char letter;
if ((letter = strs[0][i]) != strs[1][i])
break;
for (int j = 2; j < strs.Length; j++)
{
if (letter != strs[j][i])
{
maxLen = -1;
break;
}
}
if(maxLen != -1)
sb.Append(letter);
}
return sb.ToString();
}
}

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_141._Linked_List_Cycle</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_142._Linked_List_Cycle_II</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_144._Binary_Tree_Preorder_Traversal</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_145._Binary_Tree_Postorder_Traversal</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_1480._Running_Sum_of_1d_Array</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with BOM under Windows, with no BOM otherwise" />
</project>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="UserContentModel">
<attachedFolders />
<explicitIncludes />
<explicitExcludes />
</component>
</project>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RiderProjectSettingsUpdater">
<option name="vcsConfiguration" value="2" />
</component>
</project>

View File

@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoGeneratedRunConfigurationManager">
<projectFile>_15._3Sum.csproj</projectFile>
</component>
<component name="ChangeListManager">
<list default="true" id="82866301-1c54-48b2-9c86-912478ff5746" name="Changes" comment="" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ProjectId" id="2NSm8ypYphrjURy5OrzoEQDZIRZ" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;WebServerToolWindowFactoryState&quot;: &quot;false&quot;,
&quot;settings.editor.selected.configurable&quot;: &quot;SolutionBuilderGeneralOptionsPage&quot;,
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
}
}</component>
<component name="RunManager">
<configuration name="_15._3Sum" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="" />
<option name="PROGRAM_PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/_15._3Sum.csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="1" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value="" />
<method v="2">
<option name="Build" />
</method>
</configuration>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="82866301-1c54-48b2-9c86-912478ff5746" name="Changes" comment="" />
<created>1679665701935</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1679665701935</updated>
<workItem from="1679665703808" duration="5000" />
<workItem from="1680292231454" duration="4000" />
</task>
<servers />
</component>
<component name="UnityUnitTestConfiguration" currentTestLauncher="NUnit" />
<component name="VcsManagerConfiguration">
<option name="CLEAR_INITIAL_COMMIT_MESSAGE" value="true" />
</component>
</project>

8
15. 3Sum/15. 3Sum.csproj Normal file
View File

@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
</Project>

15
15. 3Sum/Program.cs Normal file
View File

@@ -0,0 +1,15 @@
using System;
namespace _15._3Sum;
class Program
{
static void Main(string[] args)
{
var res = new Solution().ThreeSum(new int[]{-3,0,-5,2,-4,-2,1,-2,-1,3,1,3,1,3,-3,-5,1});
foreach (var list in res)
{
Console.WriteLine(String.Join(" ", list));
}
}
}

63
15. 3Sum/Solution.cs Normal file
View File

@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace _15._3Sum;
public class Solution {
class SequenceComparer<T>:IEqualityComparer<IEnumerable<T>>
{
public bool Equals(IEnumerable<T> seq1,IEnumerable<T> seq2)
{
return seq1.SequenceEqual(seq2);
}
public int GetHashCode(IEnumerable<T> seq)
{
int hash = 1234567;
foreach(T elem in seq)
hash = unchecked(hash * 37 + elem.GetHashCode());
return hash;
}
}
public IList<IList<int>> ThreeSum(int[] nums)
{
Dictionary<int, int> dict = new Dictionary<int, int>();
foreach (var num in nums)
{
if (dict.ContainsKey(num))
dict[num]++;
else
dict.Add(num, 1);
}
HashSet<IList<int>> answer = new HashSet<IList<int>>(new SequenceComparer<int>());
int[] keys = dict.Keys.ToArray();
for (int i = 0; i < keys.Length; i++)
{
int countI = dict[keys[i]]-1;
for (int j = i; j < keys.Length; j++)
{
int countJ = j == i ? (countI-1) : (dict[keys[j]]-1);
int v1 = keys[i];
int v2 = keys[j];
int v3 = -(v1+v2);
if (v3 == v1)
countI--;
if (v3 == v2)
countJ--;
bool can = dict.ContainsKey(v3);
if (can && countI >= 0 && countJ >= 0)
{
var list = new List<int>() { v1, v2, v3 };
list.Sort();
answer.Add(list);
}
countI = dict[keys[i]]-1;
}
}
return answer.ToList();
}
}

View File

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

View File

@@ -0,0 +1,11 @@
// See https://aka.ms/new-console-template for more information
using _150._Evaluate_Reverse_Polish_Notation;
string[] arr = ["10", "1", "1", "2", "+", "+", "+"];
var sol = new Solution();
int n = 100000;
while(n-- > 0)
Console.WriteLine(sol.EvalRPN(["10", "1", "1", "2", "+", "+", "+"]));

View File

@@ -0,0 +1,31 @@
namespace _150._Evaluate_Reverse_Polish_Notation;
public class Solution
{
public int EvalRPN(string[] tokens)
{
var stack = new Stack<int>(tokens.Length);
foreach (var token in tokens)
{
if (int.TryParse(token, out var number))
stack.Push(number);
else
{
int right = stack.Pop();
int left = stack.Pop();
char op = token[0];
stack.Push(Calc(op, left, right));
}
}
return stack.Pop();
}
private int Calc(char op, int left, int right) => op switch
{
'+' => left + right,
'-' => left - right,
'*' => left * right,
'/' => left / right,
_ => throw new ArgumentOutOfRangeException()
};
}

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_167._Two_Sum_II___Input_Array_Is_Sorted</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -1,8 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>_18._4Sum</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

40
18. 4Sum/Program.cs Normal file
View File

@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
var sol = new Solution();
var cases = new (int[] nums, int target, int[][] expected)[]
{
// (new[] { 1, 0, -1, 0, -2, 2 }, 0, new[]
// {
// new[] { -2, -1, 1, 2 },
// new[] { -2, 0, 0, 2 },
// new[] { -1, 0, 0, 1 }
// }),
// (new[] { 2, 2, 2, 2, 2 }, 8, new[]
// {
// new[] { 2, 2, 2, 2 }
// }),
// (new[] { -3, -1, 0, 2, 4, 5 }, 2, new[]
// {
// new[] { -3, -1, 2, 4 }
// }),
(new[] { 1000000000, 1000000000, 1000000000, 1000000000 }, -294967296, Array.Empty<int[]>())
};
foreach (var (nums, target, expected) in cases)
{
var actual = sol.FourSum(nums, target);
Console.WriteLine($"nums={FormatArray(nums)}, target={target} -> {FormatResults(actual)} (expected: {FormatResults(expected)})");
}
static string FormatArray(int[] nums)
{
return $"[{string.Join(",", nums)}]";
}
static string FormatResults(IList<IList<int>> results)
{
return "[" + string.Join(",", results.Select(r => $"[{string.Join(",", r)}]")) + "]";
}

143
18. 4Sum/Solution.cs Normal file
View File

@@ -0,0 +1,143 @@
public class Solution
{
record struct TwoSumSource(int A, int B)
{
public override string ToString()
{
return $"({A}+{B}={A + B})";
}
}
record struct AnswerRow(int? N0 = null, int? N1 = null, int? N2 = null, int? N3 = null)
{
public void PushNum(int num)
{
if (N0 == null)
{
N0 = num;
}
else if (N1 == null)
{
N1 = num;
if (N0 > N1)
{
(N0, N1) = (N1, N0);
}
}
else if (N2 == null)
{
N2 = num;
if (N1 > N2)
{
(N1, N2) = (N2, N1);
}
if (N0 > N1)
{
(N0, N1) = (N1, N0);
}
}
else if (N3 == null)
{
N3 = num;
if (N2 > N3)
{
(N2, N3) = (N3, N2);
}
if (N1 > N2)
{
(N1, N2) = (N2, N1);
}
if (N0 > N1)
{
(N0, N1) = (N1, N0);
}
}
else if (num < N3)
{
N3 = num;
if (N2 > N3)
{
(N2, N3) = (N3, N2);
}
if (N1 > N2)
{
(N1, N2) = (N2, N1);
}
if (N0 > N1)
{
(N0, N1) = (N1, N0);
}
}
}
}
public IList<IList<int>> FourSum(int[] nums, int target)
{
var dict = new Dictionary<int, int>();
// суммы из двух слагаемых, все возможные
var twoSums = new Dictionary<long, HashSet<TwoSumSource>>();
for (var i = 0; i < nums.Length; i++)
{
var num1 = nums[i];
dict.TryAdd(num1, 0);
dict[num1]++;
for (var j = i + 1; j < nums.Length; j++)
{
var num2 = nums[j];
var sum = num1 + num2;
twoSums.TryAdd(sum, new HashSet<TwoSumSource>());
twoSums[sum].Add(new TwoSumSource() { A = num1, B = num2 });
}
}
var rows = new HashSet<AnswerRow>();
// словарь для требуемоего количества чисел
var needDict = new Dictionary<int, int>();
foreach (var kp1 in dict)
{
var needThreeSum = target - kp1.Key;
needDict.TryAdd(kp1.Key, 0);
needDict[kp1.Key]++;
foreach (var kp2 in dict)
{
needDict.TryAdd(kp2.Key, 0);
needDict[kp2.Key]++;
var needTwoSum = (long)needThreeSum - kp2.Key;
if (twoSums.TryGetValue(needTwoSum, out var curTwoSums))
{
foreach (var curTwoSum in curTwoSums)
{
needDict.TryAdd(curTwoSum.A, 0);
needDict[curTwoSum.A]++;
needDict.TryAdd(curTwoSum.B, 0);
needDict[curTwoSum.B]++;
if (needDict.All(kp => dict[kp.Key] >= kp.Value))
{
var row = new AnswerRow();
row.PushNum(kp1.Key);
row.PushNum(kp2.Key);
row.PushNum(curTwoSum.A);
row.PushNum(curTwoSum.B);
rows.Add(row);
}
needDict[curTwoSum.A]--;
needDict[curTwoSum.B]--;
}
}
needDict[kp2.Key]--;
}
needDict.Clear();
}
var answer = new List<IList<int>>(rows.Count);
foreach (var row in rows)
answer.Add(new List<int> { row.N0!.Value, row.N1!.Value, row.N2!.Value, row.N3!.Value });
return answer;
}
}

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_189._Rotate_Array</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_19._Remove_Nth_Node_From_End_of_List</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_190._Reverse_Bits</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_191._Number_of_1_Bits</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_198._House_Robber</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_2._Add_Two_Numbers</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -1,7 +1,7 @@
namespace _2._Add_Two_Numbers;
public class Solution {
public ListNode AddTwoNumbers(ListNode? l1, ListNode? l2)
public ListNode? AddTwoNumbers(ListNode? l1, ListNode? l2)
{
ListNode? answer = null;
ListNode? answerEnd = answer;
@@ -24,7 +24,7 @@ public class Solution {
toNext = sum / 10;
sum %= 10;
ListNode item = new ListNode(sum);
if (answer == null)
if (answer == null || answerEnd == null)
answer = answerEnd = item;
else
{
@@ -33,7 +33,7 @@ public class Solution {
}
}
if (toNext != 0)
if (toNext != 0 && answerEnd != null)
answerEnd.next = new ListNode(toNext);
return answer;
}

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_20._Valid_Parentheses</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_200._Number_of_Islands</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_203._Remove_Linked_List_Elements</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_205._Isomorphic_Strings</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_206._Reverse_Linked_List</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_21._Merge_Two_Sorted_Lists</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_217._Contains_Duplicate</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

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

View File

@@ -0,0 +1,50 @@
namespace _225._Implement_Stack_using_Queues;
public class MyStack
{
private Queue<int> _queue = new Queue<int>(256);
private int? _lastNum = null;
public MyStack()
{
}
public void Push(int x)
{
if (_lastNum == null)
{
_lastNum = x;
return;
}
int count = _queue.Count;
_queue.Enqueue(_lastNum.Value);
_lastNum = x;
while (count-- > 0)
_queue.Enqueue(_queue.Dequeue());
}
public int Pop()
{
if (_lastNum != null)
{
int res = _lastNum.Value;
_lastNum = null;
return res;
}
return _queue.Dequeue();
}
public int Top()
{
if (_lastNum != null)
return _lastNum.Value;
return _queue.Peek();
}
public bool Empty()
{
return _lastNum == null && _queue.Count == 0;
}
}

View File

@@ -0,0 +1,3 @@
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_226._Invert_Binary_Tree</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View 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>

View 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;
}
}

View File

@@ -0,0 +1,2 @@
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

View 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;
}
}

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_231._Power_of_Two</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_232._Implement_Queue_using_Stacks</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,18 +2,19 @@
public class MyQueue
{
private Stack<int> _sInput = new Stack<int>();
private Stack<int> _sOutput = new Stack<int>();
private Stack<int> _sInput = new Stack<int>(256);
private Stack<int> _sOutput = new Stack<int>(256);
public void Push(int x)
{
while (_sOutput.TryPop(out int res))
_sInput.Push(res);
_sInput.Push(x);
}
public int Pop()
{
if (_sOutput.Count > 0)
return _sOutput.Pop();
while (_sInput.TryPop(out int res))
_sOutput.Push(res);
return _sOutput.Pop();
@@ -21,6 +22,9 @@ public class MyQueue
public int Peek()
{
if (_sOutput.Count > 0)
return _sOutput.Peek();
while (_sInput.TryPop(out int res))
_sOutput.Push(res);
return _sOutput.Peek();
@@ -28,8 +32,6 @@ public class MyQueue
public bool Empty()
{
while (_sInput.TryPop(out int res))
_sOutput.Push(res);
return _sOutput.Count == 0;
return _sOutput.Count == 0 && _sInput.Count == 0;
}
}

View File

@@ -4,6 +4,11 @@ internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
int x = 5;
MyQueue obj = new MyQueue();
obj.Push(x);
int param_2 = obj.Pop();
int param_3 = obj.Peek();
bool param_4 = obj.Empty();
}
}

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_235._Lowest_Common_Ancestor_of_a_Binary_Search_Tree</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_240._Search_a_2D_Matrix_II</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_242._Valid_Anagram</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

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

View File

@@ -0,0 +1,2 @@
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

View File

@@ -0,0 +1,16 @@
public class Solution {
public int RemoveDuplicates(int[] nums) {
var k = nums.Length;
var putIndex = 0;
for(var i = 0; i < nums.Length; i++)
{
while(i < nums.Length - 1 && nums[i+1] == nums[i])
{
i++;
k--;
}
nums[putIndex++] = nums[i];
}
return k;
}
}

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_278._First_Bad_Version</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_283._Move_Zeroes</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

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

View File

@@ -0,0 +1,74 @@
static string FormatMatrix(int[][] matrix)
{
var rows = new string[matrix.Length];
for (var i = 0; i < matrix.Length; i++)
rows[i] = "[" + string.Join(",", matrix[i]) + "]";
return "[" + string.Join(",", rows) + "]";
}
var sol = new Solution();
var cases = new (int[][] input, string expected)[]
{
(
new[]
{
new[] { 1, 2 },
new[] { 3, 4 }
},
"[[24,12],[8,6]]"
),
(
new[]
{
new[] { 12345 },
new[] { 2 },
new[] { 1 }
},
"[[2],[0],[0]]"
),
(
new[]
{
new[] { 4, 8, 8 },
new[] { 6, 2, 5 },
new[] { 7, 3, 7 },
new[] { 6, 3, 5 }
},
"[[3525,7935,7935],[6465,7050,2820],[7305,585,7305],[6465,585,2820]]"
),
(
new[]
{
new[] { 4, 3, 9 },
new[] { 3, 9, 10 },
new[] { 9, 7, 8 },
new[] { 8, 4, 7 },
new[] { 6, 1, 3 }
},
"[[3255,225,75],[225,75,11178],[75,1860,7800],[7800,3255,1860],[6285,675,225]]"
),
(
new[]
{
new []{1,2,2},
new []{1,4,3}
},
"[[48,24,24],[48,12,16]]"
),
(
new[]
{
new[] { 414750857 },
new[] { 449145368 },
new[] { 767292749 }
},
"[[1462],[3103],[9436]]"
)
};
foreach (var (input, expected) in cases)
{
var actual = sol.ConstructProductMatrix(input);
Console.WriteLine($"{FormatMatrix(input)} -> {FormatMatrix(actual)} (expected: {expected})");
}

View File

@@ -0,0 +1,80 @@
public class Solution
{
struct MulInfo
{
public long Left;
public long Right;
}
public int[][] ConstructProductMatrix(int[][] grid)
{
var mod = 12345;
var table = new MulInfo[grid.Length][];
var lastRow = grid.Length - 1;
var lastCol = grid[0].Length - 1;
// прямой проход
for (var i = 0; i < grid.Length; i++)
{
table[i] = new MulInfo[grid[i].Length];
for (var j = 0; j < grid[i].Length; j++)
{
if (j == 0 && i == 0)
{
table[i][j].Left = grid[i][j] % mod;
}
else if (j > 0)
{
table[i][j].Left = table[i][j - 1].Left * grid[i][j] % mod;
}
else if (i > 0)
{
table[i][j].Left = table[i - 1][lastCol].Left * grid[i][j];
table[i][j].Left %= mod;
}
}
}
// обратный проход
for (var i = lastRow; i >= 0; i--)
{
for (var j = lastCol; j >= 0; j--)
{
if (j == lastCol && i == lastRow)
{
table[i][j].Right = grid[i][j] % mod;
}
else if (j < lastCol)
{
table[i][j].Right = table[i][j + 1].Right * grid[i][j] % mod;
}
else if (i < lastRow)
{
table[i][j].Right = table[i + 1][0].Right * grid[i][j] % mod;
}
var left = 1L;
var right = 1L;
if (i == 0 && j == 0)
left = 1;
else if (j > 0)
left = table[i][j - 1].Left;
else if (i > 0)
left = table[i - 1][lastCol].Left;
if (i == lastRow && j == lastCol)
right = 1;
else if (j < lastCol)
right = table[i][j + 1].Right;
else if (i < lastRow)
right = table[i + 1][0].Right;
grid[i][j] = (int)(left * right % mod);
}
}
return grid;
}
}

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_299._Bulls_and_Cows</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_3._Longest_Substring_Without_Repeating_Characters</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

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

View File

@@ -0,0 +1,18 @@
var sol = new Solution();
var cases = new (string s, string[] words, int[] expected)[]
{
// ("barfoothefoobarman", new[] { "foo", "bar" }, new[] { 0, 9 }),
// ("wordgoodgoodgoodbestword", new[] { "word", "good", "best", "word" }, Array.Empty<int>()),
// ("barfoofoobarthefoobarman", new[] { "bar", "foo", "the" }, new[] { 6, 9, 12 }),
("wordgoodgoodgoodbestword", new[] { "word", "good", "best", "good" }, new[] { 8 })
};
string Format(IEnumerable<int> values) => $"[{string.Join(",", values)}]";
string FormatWords(IEnumerable<string> values) => $"[{string.Join(",", values)}]";
foreach (var (s, words, expected) in cases)
{
var actual = sol.FindSubstring(s, words);
Console.WriteLine($"{s} | {FormatWords(words)} -> {Format(actual)} (expected: {Format(expected)})");
}

View File

@@ -0,0 +1,35 @@
public class Solution
{
public IList<int> FindSubstring(string s, string[] words)
{
var len = words[0].Length;
var allLen = len * words.Length;
var dict = new Dictionary<string, int>();
foreach (var word in words)
{
dict.TryAdd(word, 0);
dict[word]++;
}
var answer = new List<int>();
var windowDict = new Dictionary<string, int>();
for (var offset = 0; offset < len; offset++)
{
for (var i = offset; i <= s.Length-len; i += len)
{
var word = s[i..(i + len)];
var prevInx = i - allLen;
if (prevInx >= 0)
{
var leftWord = s[prevInx..(prevInx + len)];
windowDict[leftWord]--;
}
windowDict.TryAdd(word, 0);
windowDict[word]++;
if (dict.All(kvp => windowDict.TryGetValue(kvp.Key, out var count) && count == kvp.Value))
answer.Add(prevInx + len);
}
windowDict.Clear();
}
return answer;
}
}

View File

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

View File

@@ -0,0 +1,30 @@
var sol = new Solution();
var cases = new (int[] input, int[] expected)[]
{
(new[] { 1, 2, 3 }, new[] { 1, 3, 2 }),
(new[] { 3, 2, 1 }, new[] { 1, 2, 3 }),
(new[] { 1, 1, 5 }, new[] { 1, 5, 1 })
};
foreach (var (input, expected) in cases)
{
var nums = (int[])input.Clone();
sol.NextPermutation(nums);
var status = AreEqual(nums, expected) ? "ok" : "fail";
Console.WriteLine($"{Format(input)} -> {Format(nums)} (expected: {Format(expected)}) {status}");
}
static string Format(int[] nums) => $"[{string.Join(",", nums)}]";
static bool AreEqual(int[] left, int[] right)
{
if (left.Length != right.Length)
return false;
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
return false;
}
return true;
}

View File

@@ -0,0 +1,17 @@
public class Solution
{
public void NextPermutation(int[] nums)
{
var i = nums.Length - 2;
while(i >= 0 && nums[i] >= nums[i+1])
i--;
if(i >= 0)
{
var j = nums.Length - 1;
while(nums[i] >= nums[j])
j--;
(nums[i], nums[j]) = (nums[j], nums[i]);
}
Array.Reverse(nums, i+1, nums.Length-i-1);
}
}

View File

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

View File

@@ -0,0 +1,5 @@
var sol = new Solution();
// System.Console.WriteLine(sol.LongestValidParentheses(")()())"));
// System.Console.WriteLine(sol.LongestValidParentheses("()(()"));
System.Console.WriteLine(sol.LongestValidParentheses("()(())"));

View File

@@ -0,0 +1,43 @@
public class Solution
{
struct Item
{
public char Sym;
public int Count;
public char? PrevSym;
}
public int LongestValidParentheses(string s)
{
var stack = new Stack<Item>();
var answer = 0;
foreach (var ch in s)
{
if (stack.Count > 0 && (stack.Peek().Sym == '(' || stack.Peek().PrevSym == '(') && ch == ')')
{
var prev = stack.Pop();
var count = 2;
if (prev.Sym == '#')
{
stack.Pop();
count += prev.Count;
}
while (stack.Count > 0 && stack.Peek().Sym == '#')
count += stack.Pop().Count;
char? prevSym = null;
if (stack.Count > 0)
prevSym = stack.Peek().Sym;
stack.Push(new Item() { Sym = '#', Count = count, PrevSym = prevSym });
answer = Math.Max(answer, count);
}
else
{
stack.Push(new Item() { Sym = ch, Count = 0 });
}
}
return answer;
}
}

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_344._Reverse_String</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

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

View File

@@ -0,0 +1,4 @@
using _347._Top_K_Frequent_Elements;
var sol = new Solution();
Console.WriteLine(string.Join(", ", sol.TopKFrequent([1,1,1,2,2,3], 2)));

View File

@@ -0,0 +1,13 @@
namespace _347._Top_K_Frequent_Elements;
public class Solution
{
public int[] TopKFrequent(int[] nums, int k)
{
var dictionary = new Dictionary<int, int>();
foreach (var num in nums)
if (!dictionary.TryAdd(num, 1))
dictionary[num]++;
return dictionary.OrderByDescending(kp=>kp.Value).Take(k).Select(kp=>kp.Key).ToArray();
}
}

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_35._Search_Insert_Position</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_350._Intersection_of_Two_Arrays_II</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

View File

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

View File

@@ -0,0 +1,29 @@
var sol = new Solution();
var cases = new (int[][] grid, bool expected, string name)[]
{
(
new[]
{
new[] { 1, 4 },
new[] { 2, 3 }
},
true,
"Example 1"
),
(
new[]
{
new[] { 1, 3 },
new[] { 2, 4 }
},
false,
"Example 2"
)
};
foreach (var (grid, expected, name) in cases)
{
var actual = sol.CanPartitionGrid(grid);
Console.WriteLine($"{name}: {actual} (expected: {expected})");
}

View File

@@ -0,0 +1,49 @@
public class Solution
{
struct SumInfo
{
public long Left;
public long Right;
public long Value;
}
public bool CanPartitionGrid(int[][] grid)
{
var height = grid.Length;
var width = grid[0].Length;
var colSums = new SumInfo[width];
var rowSums = new SumInfo[height];
for (var i = 0; i < height; i++)
{
for (var j = 0; j < grid[i].Length; j++)
{
colSums[j].Value += grid[i][j];
rowSums[i].Value += grid[i][j];
}
rowSums[i].Left = rowSums[i].Value;
if (i > 0)
rowSums[i].Left += rowSums[i - 1].Left;
}
for (var i = height - 1; i >= 0; i--)
{
rowSums[i].Right = rowSums[i].Value;
if (i < height - 1)
rowSums[i].Right += rowSums[i + 1].Right;
}
for (var j = 0; j < width; j++)
{
colSums[j].Left = colSums[j].Value;
if (j > 0)
colSums[j].Left += colSums[j - 1].Left;
}
for (var j = width - 1; j >= 0; j--)
{
colSums[j].Right = colSums[j].Value;
if (j < width - 1)
colSums[j].Right += colSums[j + 1].Right;
}
return rowSums.Any(row => Math.Abs(row.Left - row.Right) == row.Value) || colSums.Any(col => Math.Abs(col.Left - col.Right) == col.Value);
}
}

View File

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

View File

@@ -0,0 +1,139 @@
var sol = new Solution();
var cases = new (int[][] grid, bool expected, string name)[]
{
(
new[]
{
new[] { 1, 4 },
new[] { 2, 3 }
},
true,
"Example 1"
),
(
new[]
{
new[] { 1, 2 },
new[] { 3, 4 }
},
true,
"Example 2"
),
(
new[]
{
new[] { 1, 2, 4 },
new[] { 2, 3, 5 }
},
false,
"Example 3"
),
(
new[]
{
new[] { 4, 1, 8 },
new[] { 3, 2, 6 }
},
false,
"Example 4"
),
(
new[]
{
new[] { 5, 5, 6, 2, 2, 2 }
},
true,
"Example 5"
),
(
new[]
{
new[] { 100000 },
new[] { 86218 },
new[] { 100000 }
},
true,
"Example 6"
),
(
new[]
{
new[] { 1, 2, 4 },
new[] { 1, 6, 6 },
new[] { 5, 6, 7 }
},
true,
"Example 7"
),
(
new[]
{
new[] { 1, 2, 1, 1, 1 },
new[] { 1, 1, 1, 2, 1 }
},
true,
"Example 8"
),
(
new[]
{
new[] { 1, 1 },
new[] { 2, 1 },
new[] { 1, 1 },
new[] { 1, 2 },
new[] { 1, 1 }
},
true,
"Example 9"
),
(
new[]
{
new[] { 10, 5, 4, 5 }
},
false,
"Example 10"
),
(
new[]
{
new[] { 1, 1 },
new[] { 2, 1 },
new[] { 4, 3 }
},
false,
"Example 11"
),
(
new[]
{
new[] { 4 },
new[] { 3 },
new[] { 4 },
new[] { 4 },
new[] { 4 }
},
false,
"Example 12"
),
(
new[]
{
new[] { 100000 },
new[] { 100000 },
new[] { 100000 },
new[] { 100000 },
new[] { 1 }
},
true,
"Example 13"
),
};
foreach (var (grid, expected, name) in cases)
{
var actual = sol.CanPartitionGrid(grid);
Console.WriteLine($"{name}: {actual} (expected: {expected})");
}

View File

@@ -0,0 +1,130 @@
public class Solution
{
struct SumInfo
{
public long Left;
public long Right;
public long Value;
// ключ - число, значение - индексы, где оно встречается
public Dictionary<long, SortedSet<int>> Nums;
}
public bool CanPartitionGrid(int[][] grid)
{
var height = grid.Length;
var width = grid[0].Length;
var colSums = new SumInfo[width];
var rowSums = new SumInfo[height];
for (var i = 0; i < height; i++)
{
for (var j = 0; j < width; j++)
{
var num = grid[i][j];
colSums[j].Value += num;
rowSums[i].Value += num;
rowSums[i].Nums ??= new Dictionary<long, SortedSet<int>>();
colSums[j].Nums ??= new Dictionary<long, SortedSet<int>>();
rowSums[i].Nums.TryAdd(num, new SortedSet<int>());
rowSums[i].Nums[num].Add(j);
colSums[j].Nums.TryAdd(num, new SortedSet<int>());
colSums[j].Nums[num].Add(i);
}
rowSums[i].Left = rowSums[i].Value;
if (i > 0)
rowSums[i].Left += rowSums[i - 1].Left;
}
for (var i = height - 1; i >= 0; i--)
{
rowSums[i].Right = rowSums[i].Value;
if (i < height - 1)
rowSums[i].Right += rowSums[i + 1].Right;
}
for (var j = 0; j < width; j++)
{
colSums[j].Left = colSums[j].Value;
if (j > 0)
colSums[j].Left += colSums[j - 1].Left;
}
for (var j = width - 1; j >= 0; j--)
{
colSums[j].Right = colSums[j].Value;
if (j < width - 1)
colSums[j].Right += colSums[j + 1].Right;
}
var answer = false;
for (var i = 0; i < rowSums.Length - 1 && !answer; i++)
{
var row = rowSums[i];
var nextRow = rowSums[i + 1];
var diff = Math.Abs(row.Left - nextRow.Right);
var edgesOnly = colSums.Length == 1;
var colLen = height;
if (diff == 0 ||
(row.Left < nextRow.Right && CanDelete(diff, colSums, i, true, i + 1 == rowSums.Length - 1, edgesOnly, colLen)) ||
(row.Left > nextRow.Right && CanDelete(diff, colSums, i, false, i == 0, edgesOnly, colLen)))
answer |= true;
}
for (var j = 0; j < colSums.Length - 1 && !answer; j++)
{
var col = colSums[j];
var nextCol = colSums[j + 1];
var diff = Math.Abs(col.Left - nextCol.Right);
// тут проход по колонкам, значит поиск элемента для удаления надо выполнять по строкам
// если j == 0 и отрезаем в левой части, то надо смотреть только первую и последнюю строку
// если j+1 == colSums.Len-1 и отрезаем в правой части, то надо смотреть только первую и последнюю строку
var edgesOnly = rowSums.Length == 1;
var rowLen = width;
if (diff == 0 ||
(col.Left < nextCol.Right && CanDelete(diff, rowSums, j, true, j + 1 == colSums.Length - 1, edgesOnly, rowLen)) ||
(col.Left > nextCol.Right && CanDelete(diff, rowSums, j, false, j == 0, edgesOnly, rowLen)))
answer |= true;
}
return answer;
}
/// <summary>
///
/// </summary>
/// <param name="target">Целевое число для поиска</param>
/// <param name="infos">Что перебирать</param>
/// <param name="idx">Индекс отсечения (для удаления справа строго больше, для удаления слева включительно)</param>
/// <param name="deleteAfterIdx">Удалять ли спарва от индекса</param>
/// <param name="firstAndLastOnly">Посмотреть только первый и последний SumInfo</param>
/// <param name="edgesOnly">В sumInfo брать только крайние элементы</param>
/// <param name="len">Количество чисел в SumInfo</param>
/// <returns></returns>
private static bool CanDelete(long target, SumInfo[] infos, int idx, bool deleteAfterIdx, bool firstAndLastOnly, bool edgesOnly, int len)
{
for (var i = 0; i < infos.Length; i++)
{
var nums = infos[i].Nums;
if (nums.TryGetValue(target, out var indexes))
{
var before = false;
var after = false;
if (edgesOnly)
{
before = indexes.Contains(0) || indexes.Contains(idx);
after = indexes.Contains(len - 1) || indexes.Contains(idx+1);
}
else
{
before = indexes.GetViewBetween(int.MinValue, idx).Count > 0;
after = indexes.GetViewBetween(idx + 1, int.MaxValue).Count > 0;
}
if ((before && !deleteAfterIdx) || (after && deleteAfterIdx))
return true;
}
// если только границы, перейти сразу к последнему элементу
if (firstAndLastOnly && i == 0)
i = Math.Max(i, infos.Length - 2);
}
return false;
}
}

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_36._Valid_Sudoku</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

Some files were not shown because too many files have changed in this diff Show More