From d713c0929bfb9d716f164be3755655a61f354318 Mon Sep 17 00:00:00 2001 From: zhousl <57696015+xieyiincuit@users.noreply.github.com> Date: Mon, 18 Jul 2022 00:09:25 +0800 Subject: [PATCH 01/31] =?UTF-8?q?[#add]=20=E6=AF=8F=E6=97=A5=E4=B8=80?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Solution/QueueSection/DayQuestion.cs | 30 +++++++++++++++++++ .../Solution/QueueSection/Program.cs | 1 + .../Solution/QueueSection/QueueSection.csproj | 10 +++++++ cSharp-source/Solution/Solution.sln | 7 +++++ .../src/1-basic/queueSection/dayQuestion.go | 1 + .../src/1-basic/queueSection/movingAverage.go | 21 +++++++++++++ 6 files changed, 70 insertions(+) create mode 100644 cSharp-source/Solution/QueueSection/DayQuestion.cs create mode 100644 cSharp-source/Solution/QueueSection/Program.cs create mode 100644 cSharp-source/Solution/QueueSection/QueueSection.csproj create mode 100644 go-source/src/1-basic/queueSection/dayQuestion.go create mode 100644 go-source/src/1-basic/queueSection/movingAverage.go diff --git a/cSharp-source/Solution/QueueSection/DayQuestion.cs b/cSharp-source/Solution/QueueSection/DayQuestion.cs new file mode 100644 index 0000000..34c0c03 --- /dev/null +++ b/cSharp-source/Solution/QueueSection/DayQuestion.cs @@ -0,0 +1,30 @@ +namespace QueueSection; + +public class DayQuestion +{ +} + +// 剑指 Offer II 041. 滑动窗口的平均值 +public class MovingAverage +{ + private int[] arr; + private int _size, sum, rear, front; + + /** Initialize your data structure here. */ + public MovingAverage(int size) + { + this.arr = new int [10010]; + this._size = size; + } + + public double Next(int val) + { + sum += arr[rear++] = val; + if (rear - front > _size) + { + sum -= arr[front]; + front++; + } + return (double)sum / (rear - front); + } +} \ No newline at end of file diff --git a/cSharp-source/Solution/QueueSection/Program.cs b/cSharp-source/Solution/QueueSection/Program.cs new file mode 100644 index 0000000..837131c --- /dev/null +++ b/cSharp-source/Solution/QueueSection/Program.cs @@ -0,0 +1 @@ +Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/QueueSection/QueueSection.csproj b/cSharp-source/Solution/QueueSection/QueueSection.csproj new file mode 100644 index 0000000..b9de063 --- /dev/null +++ b/cSharp-source/Solution/QueueSection/QueueSection.csproj @@ -0,0 +1,10 @@ + + + + Exe + net6.0 + enable + enable + + + diff --git a/cSharp-source/Solution/Solution.sln b/cSharp-source/Solution/Solution.sln index 90bc6bf..bda769b 100644 --- a/cSharp-source/Solution/Solution.sln +++ b/cSharp-source/Solution/Solution.sln @@ -23,6 +23,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "2-External", "2-External", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrieSection", "TrieSection\TrieSection.csproj", "{6F24B5FF-4F1A-4E65-9959-118DAA01C460}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QueueSection", "QueueSection\QueueSection.csproj", "{1F97AF7C-41C2-48D5-88E1-2DF39E236D50}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -57,6 +59,10 @@ Global {6F24B5FF-4F1A-4E65-9959-118DAA01C460}.Debug|Any CPU.Build.0 = Debug|Any CPU {6F24B5FF-4F1A-4E65-9959-118DAA01C460}.Release|Any CPU.ActiveCfg = Release|Any CPU {6F24B5FF-4F1A-4E65-9959-118DAA01C460}.Release|Any CPU.Build.0 = Release|Any CPU + {1F97AF7C-41C2-48D5-88E1-2DF39E236D50}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1F97AF7C-41C2-48D5-88E1-2DF39E236D50}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1F97AF7C-41C2-48D5-88E1-2DF39E236D50}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1F97AF7C-41C2-48D5-88E1-2DF39E236D50}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -72,5 +78,6 @@ Global {CE4BAB7B-6825-4927-A48A-28DEB8E80B47} = {5D2E938C-2618-4DD9-A439-F193655266A0} {5D630232-7215-4FCF-A5DA-7B943B61BD58} = {5D2E938C-2618-4DD9-A439-F193655266A0} {6F24B5FF-4F1A-4E65-9959-118DAA01C460} = {5D2E938C-2618-4DD9-A439-F193655266A0} + {1F97AF7C-41C2-48D5-88E1-2DF39E236D50} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} EndGlobalSection EndGlobal diff --git a/go-source/src/1-basic/queueSection/dayQuestion.go b/go-source/src/1-basic/queueSection/dayQuestion.go new file mode 100644 index 0000000..ad1941f --- /dev/null +++ b/go-source/src/1-basic/queueSection/dayQuestion.go @@ -0,0 +1 @@ +package queueSection diff --git a/go-source/src/1-basic/queueSection/movingAverage.go b/go-source/src/1-basic/queueSection/movingAverage.go new file mode 100644 index 0000000..90e58f6 --- /dev/null +++ b/go-source/src/1-basic/queueSection/movingAverage.go @@ -0,0 +1,21 @@ +package queueSection + +type MovingAverage struct { + Queue []int + Size, Sum int +} + +func Constructor(size int) MovingAverage { + return MovingAverage{[]int{}, size, 0} +} + +func (this *MovingAverage) Next(val int) float64 { + // 开始滑动 + if len(this.Queue) == this.Size { + this.Sum -= this.Queue[0] + this.Queue = this.Queue[1:] + } + this.Queue = append(this.Queue, val) + this.Sum += val + return float64(this.Sum) / float64(len(this.Queue)) +} -- Gitee From 9ca984167bf568cde0b9a5280bce5836b5f5ce6b Mon Sep 17 00:00:00 2001 From: zhousl Date: Mon, 18 Jul 2022 18:29:58 +0800 Subject: [PATCH 02/31] =?UTF-8?q?[#add]=20=E6=AF=8F=E6=97=A5=E4=B8=80?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Solution/ArraySection/DayQuestion.cs | 33 +++++++++++++++++++ go-source/src/0-test/algorithm_test.go | 33 +++++++++++++++++++ .../src/1-basic/arraySection/dayQuestion.go | 26 +++++++++++++++ 3 files changed, 92 insertions(+) create mode 100644 go-source/src/0-test/algorithm_test.go diff --git a/cSharp-source/Solution/ArraySection/DayQuestion.cs b/cSharp-source/Solution/ArraySection/DayQuestion.cs index b6cc491..12fde42 100644 --- a/cSharp-source/Solution/ArraySection/DayQuestion.cs +++ b/cSharp-source/Solution/ArraySection/DayQuestion.cs @@ -267,4 +267,37 @@ public class DayQuestion } #endregion + + #region day 7.18 + + // 565. Array Nesting + public int ArrayNesting(int[] nums) + { + int res = 1; + bool[] visited = new bool[nums.Length]; + + for (int i = 0; i < nums.Length; i++) + { + // 乱序超过一半,则全为乱序了 + if (res > nums.Length / 2) + return res; + // 若该访问点被某序列访问过,那么以这个元素为头的序列肯定不为最长 + if (visited[nums[i]] == true) + continue; + + int len = 1; + int next = nums[nums[i]]; + while (next != nums[i]) + { + visited[next] = true; + + len++; + next = nums[next]; + } + res = len > res ? len : res; + } + return res; + } + + #endregion } \ No newline at end of file diff --git a/go-source/src/0-test/algorithm_test.go b/go-source/src/0-test/algorithm_test.go new file mode 100644 index 0000000..d6e9446 --- /dev/null +++ b/go-source/src/0-test/algorithm_test.go @@ -0,0 +1,33 @@ +package __test + +import ( + "testing" +) + +func BenchmarkOn(b *testing.B) { + b.ResetTimer() + var res int64 + for i := 0; i < b.N; i++ { + res++ + } +} + +func BenchmarkO2n(b *testing.B) { + b.ResetTimer() + var res int64 + for i := 0; i < b.N; i++ { + for j := 0; j < b.N; j++ { + res++ + } + } +} + +func BenchmarkOlogn(b *testing.B) { + b.ResetTimer() + var res int64 + for i := 0; i < b.N; i++ { + for j := 1; j < b.N; j = j * 2 { + res++ + } + } +} diff --git a/go-source/src/1-basic/arraySection/dayQuestion.go b/go-source/src/1-basic/arraySection/dayQuestion.go index 771f995..bebb75c 100644 --- a/go-source/src/1-basic/arraySection/dayQuestion.go +++ b/go-source/src/1-basic/arraySection/dayQuestion.go @@ -170,3 +170,29 @@ func wiggleSort(nums []int) { i-- } } + +// 565. Array Nesting +func arrayNesting(nums []int) int { + res := 1 + visited := make([]bool, len(nums)) + for i := 0; i < len(nums); i++ { + if res > len(nums)/2 { + return res + } + if visited[nums[i]] == true { + continue + } + + maxLen := 1 + next := nums[nums[i]] + for next != nums[i] { + visited[next] = true + maxLen++ + next = nums[next] + } + if maxLen > res { + res = maxLen + } + } + return res +} -- Gitee From 0e8cbb5582e2ca477e5b22bff4070d4d689fea1d Mon Sep 17 00:00:00 2001 From: zhousl Date: Tue, 19 Jul 2022 17:19:27 +0800 Subject: [PATCH 03/31] =?UTF-8?q?[#add]=20=E6=AF=8F=E6=97=A5=E4=B8=80?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../orderSetSection/myCalendarTwo.go | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 go-source/src/2-external/orderSetSection/myCalendarTwo.go diff --git a/go-source/src/2-external/orderSetSection/myCalendarTwo.go b/go-source/src/2-external/orderSetSection/myCalendarTwo.go new file mode 100644 index 0000000..ea4d33a --- /dev/null +++ b/go-source/src/2-external/orderSetSection/myCalendarTwo.go @@ -0,0 +1,43 @@ +package orderSetSection + +type tuple struct { + left int + right int +} +type MyCalendarTwo struct { + booked []tuple + overlaps []tuple +} + +func Constructor() MyCalendarTwo { + return MyCalendarTwo{} +} + +func (c *MyCalendarTwo) Book(start int, end int) bool { + for _, p := range c.overlaps { + if p.left < end && start < p.right { + return false + } + } + for _, b := range c.booked { + if b.left < end && start < b.right { + c.overlaps = append(c.overlaps, tuple{left: max(b.left, start), right: min(b.right, end)}) + } + } + c.booked = append(c.booked, tuple{start, end}) + return true +} + +func min(a, b int) int { + if a > b { + return b + } + return a +} + +func max(a, b int) int { + if b > a { + return b + } + return a +} -- Gitee From d002d67358bc975c6b7ce77a77750599b263968c Mon Sep 17 00:00:00 2001 From: zhousl Date: Tue, 19 Jul 2022 17:20:27 +0800 Subject: [PATCH 04/31] =?UTF-8?q?[#add]=20=E6=AF=8F=E6=97=A5=E4=B8=80?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Solution/OrderSetSection/MyClendarTwo.cs | 39 +++++++++++++++ .../OrderSetSection/OrderSetSection.csproj | 10 ++++ .../Solution/OrderSetSection/Program.cs | 1 + cSharp-source/Solution/Solution.sln | 21 +++++--- .../Solution/StackSection/DayQuestions.cs | 49 +++++++++++++++++++ .../Solution/StackSection/Program.cs | 9 ++++ .../Solution/StackSection/StackSection.csproj | 10 ++++ 7 files changed, 132 insertions(+), 7 deletions(-) create mode 100644 cSharp-source/Solution/OrderSetSection/MyClendarTwo.cs create mode 100644 cSharp-source/Solution/OrderSetSection/OrderSetSection.csproj create mode 100644 cSharp-source/Solution/OrderSetSection/Program.cs create mode 100644 cSharp-source/Solution/StackSection/DayQuestions.cs create mode 100644 cSharp-source/Solution/StackSection/Program.cs create mode 100644 cSharp-source/Solution/StackSection/StackSection.csproj diff --git a/cSharp-source/Solution/OrderSetSection/MyClendarTwo.cs b/cSharp-source/Solution/OrderSetSection/MyClendarTwo.cs new file mode 100644 index 0000000..b29b2e1 --- /dev/null +++ b/cSharp-source/Solution/OrderSetSection/MyClendarTwo.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrderSetSection; + +public class MyCalendarTwo +{ + private SortedDictionary calendar; + + public MyCalendarTwo() + { + calendar = new SortedDictionary(); + } + + public bool Book(int start, int end) + { + int res = 0, maxBook = 0; + + if (!calendar.TryAdd(start, 1)) calendar[start] += 1; + if (!calendar.TryAdd(end, -1)) calendar[end] -= 1; + + foreach (var item in calendar) + { + maxBook += item.Value; + res = Math.Max(maxBook, res); + if (maxBook > 2) + { + calendar[start] -= 1; + calendar[end] += 1; + return false; + } + } + + return true; + } +} diff --git a/cSharp-source/Solution/OrderSetSection/OrderSetSection.csproj b/cSharp-source/Solution/OrderSetSection/OrderSetSection.csproj new file mode 100644 index 0000000..74abf5c --- /dev/null +++ b/cSharp-source/Solution/OrderSetSection/OrderSetSection.csproj @@ -0,0 +1,10 @@ + + + + Exe + net6.0 + enable + enable + + + diff --git a/cSharp-source/Solution/OrderSetSection/Program.cs b/cSharp-source/Solution/OrderSetSection/Program.cs new file mode 100644 index 0000000..837131c --- /dev/null +++ b/cSharp-source/Solution/OrderSetSection/Program.cs @@ -0,0 +1 @@ +Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/Solution.sln b/cSharp-source/Solution/Solution.sln index bda769b..f410dc0 100644 --- a/cSharp-source/Solution/Solution.sln +++ b/cSharp-source/Solution/Solution.sln @@ -13,7 +13,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TreeSection", "TreeSection\ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DPSection", "DPSection\DPSection.csproj", "{CE4BAB7B-6825-4927-A48A-28DEB8E80B47}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EncodeSection", "EncodeSection\EncodeSection.csproj", "{5D630232-7215-4FCF-A5DA-7B943B61BD58}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EncodeSection", "EncodeSection\EncodeSection.csproj", "{5D630232-7215-4FCF-A5DA-7B943B61BD58}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "0-Test", "0-Test", "{06382AED-685A-4336-B553-DDA7C3A8C616}" EndProject @@ -21,9 +21,11 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "1-Basic", "1-Basic", "{9CFD EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "2-External", "2-External", "{5D2E938C-2618-4DD9-A439-F193655266A0}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrieSection", "TrieSection\TrieSection.csproj", "{6F24B5FF-4F1A-4E65-9959-118DAA01C460}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TrieSection", "TrieSection\TrieSection.csproj", "{6F24B5FF-4F1A-4E65-9959-118DAA01C460}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QueueSection", "QueueSection\QueueSection.csproj", "{1F97AF7C-41C2-48D5-88E1-2DF39E236D50}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QueueSection", "QueueSection\QueueSection.csproj", "{1F97AF7C-41C2-48D5-88E1-2DF39E236D50}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OrderSetSection", "OrderSetSection\OrderSetSection.csproj", "{96EBA533-AA18-440E-A1A0-37ED75FDBE94}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -63,21 +65,26 @@ Global {1F97AF7C-41C2-48D5-88E1-2DF39E236D50}.Debug|Any CPU.Build.0 = Debug|Any CPU {1F97AF7C-41C2-48D5-88E1-2DF39E236D50}.Release|Any CPU.ActiveCfg = Release|Any CPU {1F97AF7C-41C2-48D5-88E1-2DF39E236D50}.Release|Any CPU.Build.0 = Release|Any CPU + {96EBA533-AA18-440E-A1A0-37ED75FDBE94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {96EBA533-AA18-440E-A1A0-37ED75FDBE94}.Debug|Any CPU.Build.0 = Debug|Any CPU + {96EBA533-AA18-440E-A1A0-37ED75FDBE94}.Release|Any CPU.ActiveCfg = Release|Any CPU + {96EBA533-AA18-440E-A1A0-37ED75FDBE94}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {B95AEA45-E93F-42C8-990A-4C410797B0C6} - EndGlobalSection GlobalSection(NestedProjects) = preSolution - {897AB4BA-47B7-4AAE-9003-7FA7E6B6E51D} = {06382AED-685A-4336-B553-DDA7C3A8C616} {F1BDFC33-95C2-48D4-8A36-3476BCE8DF87} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} + {897AB4BA-47B7-4AAE-9003-7FA7E6B6E51D} = {06382AED-685A-4336-B553-DDA7C3A8C616} {B7608955-BC27-45FA-824E-EC3500CBB69F} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} {D3B21535-A822-4005-A2DA-9F236EF19C43} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} {CE4BAB7B-6825-4927-A48A-28DEB8E80B47} = {5D2E938C-2618-4DD9-A439-F193655266A0} {5D630232-7215-4FCF-A5DA-7B943B61BD58} = {5D2E938C-2618-4DD9-A439-F193655266A0} {6F24B5FF-4F1A-4E65-9959-118DAA01C460} = {5D2E938C-2618-4DD9-A439-F193655266A0} {1F97AF7C-41C2-48D5-88E1-2DF39E236D50} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} + {96EBA533-AA18-440E-A1A0-37ED75FDBE94} = {5D2E938C-2618-4DD9-A439-F193655266A0} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B95AEA45-E93F-42C8-990A-4C410797B0C6} EndGlobalSection EndGlobal diff --git a/cSharp-source/Solution/StackSection/DayQuestions.cs b/cSharp-source/Solution/StackSection/DayQuestions.cs new file mode 100644 index 0000000..ee4b3b1 --- /dev/null +++ b/cSharp-source/Solution/StackSection/DayQuestions.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StackSection; + +public class DayQuestions +{ + #region day 7.13 + + // 735. Asteroid Collision + /* + We are given an array asteroids of integers representing asteroids in a row. + For each asteroid, the absolute value represents its size, + and the sign represents its direction (positive meaning right, negative meaning left). + Each asteroid moves at the same speed. + Find out the state of the asteroids after all collisions. + If two asteroids meet, the smaller one will explode. + If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. + */ + public int[] AsteroidCollision(int[] asteroids) + { + var stack = new Stack(); + + foreach (var num in asteroids) + { + if (num < 0) stack.Push(num); + else + { + // 被撞 不进栈 + if (stack.Count > 0 && stack.Peek() > Math.Abs(num)) continue; + else if (stack.Count > 0 && stack.Peek() > 0 && stack.Peek() == Math.Abs(num)) stack.Pop(); + + while (stack.Count > 0 && stack.Peek() > 0 && stack.Peek() < Math.Abs(num)) stack.Pop(); + } + } + + var res = new int[stack.Count]; + for (int i = stack.Count - 1; i > 0; i--) + { + res[i] = stack.Pop(); + } + return res; + } + + #endregion +} \ No newline at end of file diff --git a/cSharp-source/Solution/StackSection/Program.cs b/cSharp-source/Solution/StackSection/Program.cs new file mode 100644 index 0000000..be38953 --- /dev/null +++ b/cSharp-source/Solution/StackSection/Program.cs @@ -0,0 +1,9 @@ +namespace StackSection; + +internal class Program +{ + static void Main(string[] args) + { + Console.WriteLine("Hello, World!"); + } +} diff --git a/cSharp-source/Solution/StackSection/StackSection.csproj b/cSharp-source/Solution/StackSection/StackSection.csproj new file mode 100644 index 0000000..74abf5c --- /dev/null +++ b/cSharp-source/Solution/StackSection/StackSection.csproj @@ -0,0 +1,10 @@ + + + + Exe + net6.0 + enable + enable + + + -- Gitee From a7f20dfb14ad8b635120c16540a7e92962ce3412 Mon Sep 17 00:00:00 2001 From: zhousl Date: Wed, 20 Jul 2022 18:51:59 +0800 Subject: [PATCH 05/31] =?UTF-8?q?[#add]=20=E6=AF=8F=E6=97=A5=E4=B8=80?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cSharp-source/Solution/ArraySection/Matrix.cs | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/cSharp-source/Solution/ArraySection/Matrix.cs b/cSharp-source/Solution/ArraySection/Matrix.cs index 264373d..d975ea6 100644 --- a/cSharp-source/Solution/ArraySection/Matrix.cs +++ b/cSharp-source/Solution/ArraySection/Matrix.cs @@ -2,6 +2,9 @@ public class Matrix { + #region 59 + + // 59. Spiral Matrix II // Given a positive integer n, generate an n x n matrix filled with elements // from 1 to n2 in spiral order. @@ -66,6 +69,10 @@ public class Matrix return matrix; } + #endregion + + #region 1257 + // 1252. Cells with Odd Values in a Matrix // There is an m x n matrix that is initialized to all 0's. @@ -93,4 +100,45 @@ public class Matrix return (oddRow * n) + (oddCol * m) - 2 * (oddCol * oddRow); } + + #endregion + + #region 1260 + + //Given a 2D grid of size m x n and an integer k.You need to shift the grid k times. + + //In one shift operation: + //Element at grid[i][j] moves to grid[i][j + 1]. + //Element at grid[i][n - 1] moves to grid[i + 1][0]. + //Element at grid[m - 1][n - 1] moves to grid[0][0]. + //Return the 2D grid after applying shift operation k times. + + public IList> ShiftGrid(int[][] grid, int k) + { + int[] nums = new int[grid[0].Length * grid.Length]; + + foreach (var row in grid) + { + foreach (var num in row) + { + k %= nums.Length; + nums[k++] = num; + } + } + + IList> result = new List>(nums.Length); + k = 0; + for (int i = 0; i < grid.Length; i++) + { + var tempList = new List(grid[0].Length); + for (int j = 0; j < grid[0].Length; j++) + { + tempList.Add(nums[k++]); + } + result.Add(tempList); + } + return result; + } + + #endregion } \ No newline at end of file -- Gitee From ef9c6054a0827561435d783ac6c7c82348e3da41 Mon Sep 17 00:00:00 2001 From: zhousl Date: Thu, 21 Jul 2022 18:38:27 +0800 Subject: [PATCH 06/31] =?UTF-8?q?[#update]=20=E6=AF=8F=E6=97=A5=E4=B8=80?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cSharp-source/Solution/.editorconfig | 77 +++++++++++++++++++ cSharp-source/Solution/Solution.sln | 7 +- .../Solution/TreeSection/DayQuestion.cs | 14 ++++ .../Solution/TreeSection/TreeSection.csproj | 8 ++ 4 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 cSharp-source/Solution/.editorconfig diff --git a/cSharp-source/Solution/.editorconfig b/cSharp-source/Solution/.editorconfig new file mode 100644 index 0000000..9ecd26b --- /dev/null +++ b/cSharp-source/Solution/.editorconfig @@ -0,0 +1,77 @@ +[*.cs] + +# CS8603: Possible null reference return. +dotnet_diagnostic.CS8603.severity = none +csharp_indent_labels = one_less_than_current +csharp_using_directive_placement = outside_namespace:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_prefer_braces = true:silent +csharp_style_namespace_declarations = file_scoped:silent +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = false:silent + +[*.{cs,vb}] +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +end_of_line = crlf +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +[*.{cs,vb}] +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Naming styles + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case diff --git a/cSharp-source/Solution/Solution.sln b/cSharp-source/Solution/Solution.sln index f410dc0..8429c6b 100644 --- a/cSharp-source/Solution/Solution.sln +++ b/cSharp-source/Solution/Solution.sln @@ -25,7 +25,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TrieSection", "TrieSection\ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QueueSection", "QueueSection\QueueSection.csproj", "{1F97AF7C-41C2-48D5-88E1-2DF39E236D50}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OrderSetSection", "OrderSetSection\OrderSetSection.csproj", "{96EBA533-AA18-440E-A1A0-37ED75FDBE94}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OrderSetSection", "OrderSetSection\OrderSetSection.csproj", "{96EBA533-AA18-440E-A1A0-37ED75FDBE94}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{4A4A64FA-723A-48CE-960C-CE3E0E60F364}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/cSharp-source/Solution/TreeSection/DayQuestion.cs b/cSharp-source/Solution/TreeSection/DayQuestion.cs index d9ad04c..eff6639 100644 --- a/cSharp-source/Solution/TreeSection/DayQuestion.cs +++ b/cSharp-source/Solution/TreeSection/DayQuestion.cs @@ -59,4 +59,18 @@ public class DayQuestion } #endregion + + #region day 7.21 + + //814. Binary Tree Pruning + public TreeNode PruneTree(TreeNode root) + { + if (root == null) return null; + root.left = PruneTree(root.left); + root.right = PruneTree(root.right); + if (root.left == null && root.right == null && root.val == 0) root = null; + return root; + } + + #endregion } diff --git a/cSharp-source/Solution/TreeSection/TreeSection.csproj b/cSharp-source/Solution/TreeSection/TreeSection.csproj index b9de063..a91a69e 100644 --- a/cSharp-source/Solution/TreeSection/TreeSection.csproj +++ b/cSharp-source/Solution/TreeSection/TreeSection.csproj @@ -7,4 +7,12 @@ enable + + 1701;1702;8600 + + + + 1701;1702;8600 + + -- Gitee From fe63a35b86c77c5003b44bd7ddaf3461cbce939d Mon Sep 17 00:00:00 2001 From: zhousl Date: Mon, 25 Jul 2022 18:58:43 +0800 Subject: [PATCH 07/31] =?UTF-8?q?[#add]=20=E6=AF=8F=E6=97=A5=E4=B8=80?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Solution/ArraySection/DayQuestion.cs | 39 +++++++++++++++++ .../Solution/TreeSection/DayQuestion.cs | 6 +++ go-source/src/1-basic/arraySection/matrix.go | 34 +++++++++++++-- .../src/1-basic/treeSection/cbtInserter.go | 43 +++++++++++++++++++ 4 files changed, 118 insertions(+), 4 deletions(-) create mode 100644 go-source/src/1-basic/treeSection/cbtInserter.go diff --git a/cSharp-source/Solution/ArraySection/DayQuestion.cs b/cSharp-source/Solution/ArraySection/DayQuestion.cs index 12fde42..2e41a15 100644 --- a/cSharp-source/Solution/ArraySection/DayQuestion.cs +++ b/cSharp-source/Solution/ArraySection/DayQuestion.cs @@ -300,4 +300,43 @@ public class DayQuestion } #endregion + + #region day 7.22 + + //757. Set Intersection Size At Least Two + //An integer interval[a, b] (for integers a o1[0] == o2[0] ? o2[1].CompareTo(o1[1]) : o1[0].CompareTo(o2[0])); + var n = intervals.Length; + + var cur = intervals[n - 1][0]; + var next = intervals[n - 1][0] + 1; + var ans = 2; + + for (int i = n - 2; i >= 0; i--) + { + if (intervals[i][1] >= next) continue; + else if (intervals[i][1] < cur) + { + cur = intervals[i][0]; + next = intervals[i][0] + 1; + ans += 2; + } + else + { + next = cur; + cur = intervals[i][0]; + ans++; + } + } + return ans; + } + + #endregion } \ No newline at end of file diff --git a/cSharp-source/Solution/TreeSection/DayQuestion.cs b/cSharp-source/Solution/TreeSection/DayQuestion.cs index eff6639..cc475a0 100644 --- a/cSharp-source/Solution/TreeSection/DayQuestion.cs +++ b/cSharp-source/Solution/TreeSection/DayQuestion.cs @@ -73,4 +73,10 @@ public class DayQuestion } #endregion + + #region day 7.25 + + // 919. Complete Binary Tree Inserter + + #endregion } diff --git a/go-source/src/1-basic/arraySection/matrix.go b/go-source/src/1-basic/arraySection/matrix.go index efadcbe..6887265 100644 --- a/go-source/src/1-basic/arraySection/matrix.go +++ b/go-source/src/1-basic/arraySection/matrix.go @@ -2,13 +2,11 @@ package arraySection // Given a positive integer n, generate an n x n matrix filled with elements // from 1 to n2 in spiral order. - // Input: n = 3 // Output: [[1,2,3],[8,9,4],[7,6,5]] // // Input: n = 1 // Output: [[1]] - func generateMatrix(n int) [][]int { left, right := 0, n-1 top, bottom := 0, n-1 @@ -44,6 +42,34 @@ func generateMatrix(n int) [][]int { return matrix } -func Invoke() { - generateMatrix(3) +/* +Given a 2D grid of size m x n and an integer k.You need to shift the grid k times. + +In one shift operation: +Element at grid[i][j] moves to grid[i][j + 1]. +Element at grid[i][n - 1] moves to grid[i + 1][0]. +Element at grid[m - 1][n - 1] moves to grid[0][0]. +Return the 2D grid after applying shift operation k times. +*/ + +func shiftGrid(grid [][]int, k int) [][]int { + gridSize := len(grid) * len(grid[0]) + nums := make([]int, gridSize) + + for i := 0; i < len(grid); i++ { + for j := 0; j < len(grid[0]); j++ { + k %= gridSize + nums[k] = grid[i][j] + k++ + } + } + + k = 0 + for i := 0; i < len(grid); i++ { + for j := 0; j < len(grid[0]); j++ { + grid[i][j] = nums[k] + k++ + } + } + return grid } diff --git a/go-source/src/1-basic/treeSection/cbtInserter.go b/go-source/src/1-basic/treeSection/cbtInserter.go new file mode 100644 index 0000000..6ce6907 --- /dev/null +++ b/go-source/src/1-basic/treeSection/cbtInserter.go @@ -0,0 +1,43 @@ +package treeSection + +type CBTInserter struct { + Root *TreeNode + Queue []*TreeNode +} + +func Constructor(root *TreeNode) CBTInserter { + var queue []*TreeNode + temp := []*TreeNode{root} + + for len(temp) > 0 { + cur := temp[0] + temp = temp[1:] + if cur.Left != nil { + temp = append(temp, cur.Left) + } + if cur.Right != nil { + temp = append(temp, cur.Right) + } + if cur.Left == nil || cur.Right == nil { + queue = append(queue, cur) + } + } + return CBTInserter{root, queue} +} + +func (this *CBTInserter) Insert(val int) int { + node := &TreeNode{Val: val} + cur := this.Queue[0] + if cur.Left == nil { + cur.Left = node + } else if cur.Right == nil { + cur.Right = node + this.Queue = this.Queue[1:] + } + this.Queue = append(this.Queue, node) + return cur.Val +} + +func (this *CBTInserter) Get_root() *TreeNode { + return this.Root +} -- Gitee From 5234814379056319de9e90eb9e06315e03193359 Mon Sep 17 00:00:00 2001 From: zhousl <57696015+xieyiincuit@users.noreply.github.com> Date: Tue, 26 Jul 2022 21:51:37 +0800 Subject: [PATCH 08/31] =?UTF-8?q?[#add]=20=E6=8A=84=E4=BA=86=E4=B8=80?= =?UTF-8?q?=E9=81=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Solution/OrderSetSection/SkipList.cs | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 cSharp-source/Solution/OrderSetSection/SkipList.cs diff --git a/cSharp-source/Solution/OrderSetSection/SkipList.cs b/cSharp-source/Solution/OrderSetSection/SkipList.cs new file mode 100644 index 0000000..041d19e --- /dev/null +++ b/cSharp-source/Solution/OrderSetSection/SkipList.cs @@ -0,0 +1,67 @@ +namespace OrderSetSection; + +public class SkipList +{ + private const int level = 10; + private Random _random = new Random(); + + class Node + { + public int val { get; set; } + public Node[] ne { get; set; } = new Node[level]; + + public Node(int _val) + { + val = _val; + } + } + + private Node se = new Node(-1); + + + /// + /// 查找出每一层比 target 严格小的最后一个节点,将其存成 ns 数组。 + /// 即 ns[i] 为 level=i 层严格比 target 小的最后一个节点。 + /// + /// + /// + void Find(int target, Node[] ns) + { + Node cur = se; + for (int i = level - 1; i >= 0; i--) + { + while (cur.ne[i] != null && cur.ne[i].val < target) cur = cur.ne[i]; + ns[i] = cur; // 找到大于target的链表层 + } + } + + public bool Search(int t) + { + Node[] ns = new Node[level]; + Find(t, ns); + return ns[0].ne[0] != null && ns[0].ne[0].val == t; + } + + public void Add(int t) + { + Node[] ns = new Node[level]; + Find(t, ns); + Node node = new Node(t); + for (int i = 0; i < level; i++) + { + node.ne[i] = ns[i].ne[i]; + ns[i].ne[i] = node; + if (_random.Next(2) == 0) break; + } + } + + public Boolean Erase(int t) + { + Node[] ns = new Node[level]; + Find(t, ns); + Node node = ns[0].ne[0]; + if (node == null || node.val != t) return false; + for (int i = 0; i < level && ns[i].ne[i] == node; i++) ns[i].ne[i] = ns[i].ne[i].ne[i]; + return true; + } +} \ No newline at end of file -- Gitee From 15bc219fc6b9538ab02bd30308e082b5c8ba643b Mon Sep 17 00:00:00 2001 From: zhousl Date: Wed, 27 Jul 2022 14:02:38 +0800 Subject: [PATCH 09/31] [#update] nothing --- go-source/src/1-basic/treeSection/dayQuestion.go | 6 +++--- go-source/src/1-basic/treeSection/findTreeNode.go | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go-source/src/1-basic/treeSection/dayQuestion.go b/go-source/src/1-basic/treeSection/dayQuestion.go index 6456a37..a1b47ba 100644 --- a/go-source/src/1-basic/treeSection/dayQuestion.go +++ b/go-source/src/1-basic/treeSection/dayQuestion.go @@ -1,12 +1,12 @@ package treeSection //515. Find The Largest Value in Each Tree Row -// Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed) +// Given the Root of a binary tree, return an array of the largest value in each row of the tree (0-indexed) -//Input: root = [1,3,2,5,3,null,9] +//Input: Root = [1,3,2,5,3,null,9] //Output: [1,3,9] -//Input: root = [1,2,3] +//Input: Root = [1,2,3] //Output: [1,3] func largestValues(root *TreeNode) []int { var res []int diff --git a/go-source/src/1-basic/treeSection/findTreeNode.go b/go-source/src/1-basic/treeSection/findTreeNode.go index d1a3b78..ca5a127 100644 --- a/go-source/src/1-basic/treeSection/findTreeNode.go +++ b/go-source/src/1-basic/treeSection/findTreeNode.go @@ -1,6 +1,6 @@ package treeSection -// Given the root of a binary tree, return the leftmost value in the last row of the tree. +// Given the Root of a binary tree, return the leftmost value in the last row of the tree. func findBottomLeftValue(root *TreeNode) (ans int) { queue := []*TreeNode{root} for len(queue) > 0 { -- Gitee From c10eac4f048c3b0759bcb98468da1c9a474b721c Mon Sep 17 00:00:00 2001 From: zhousl Date: Wed, 27 Jul 2022 14:03:21 +0800 Subject: [PATCH 10/31] [#update] file structure --- .../AlgorithmTest/AlgorithmTest.csproj | 30 -- .../Solution/AlgorithmTest/ArrayTest.cs | 10 - .../Solution/AlgorithmTest/Usings.cs | 2 - .../Solution/ArraySection/ArraySection.csproj | 10 - .../Solution/ArraySection/DayQuestion.cs | 342 ------------------ .../Solution/ArraySection/GlobalUsings.cs | 2 - cSharp-source/Solution/ArraySection/Matrix.cs | 144 -------- .../Solution/ArraySection/Program.cs | 1 - .../Solution/DPSection/DPSection.csproj | 10 - .../Solution/DPSection/DayQuestion.cs | 98 ----- cSharp-source/Solution/DPSection/Program.cs | 1 - .../Solution/EncodeSection/DayQuestion.cs | 49 --- .../EncodeSection/EncodeSection.csproj | 10 - .../Solution/LinkSection/LinkRemove.cs | 20 - .../Solution/LinkSection/LinkSection.csproj | 10 - .../Solution/LinkSection/ListNode.cs | 15 - cSharp-source/Solution/LinkSection/Program.cs | 1 - .../Solution/OrderSetSection/MyClendarTwo.cs | 39 -- .../OrderSetSection/OrderSetSection.csproj | 10 - .../Solution/OrderSetSection/Program.cs | 1 - .../Solution/OrderSetSection/SkipList.cs | 67 ---- .../Solution/QueueSection/DayQuestion.cs | 30 -- .../Solution/QueueSection/Program.cs | 1 - .../Solution/QueueSection/QueueSection.csproj | 10 - cSharp-source/Solution/Solution.sln | 136 +++---- .../Solution/StackSection/DayQuestions.cs | 49 --- .../Solution/StackSection/Program.cs | 9 - .../Solution/StackSection/StackSection.csproj | 10 - .../Solution/TreeSection/DayQuestion.cs | 82 ----- .../Solution/TreeSection/FindTreeNode.cs | 57 --- cSharp-source/Solution/TreeSection/Program.cs | 1 - .../Solution/TreeSection/TreeNode.cs | 16 - .../Solution/TreeSection/TreeSection.csproj | 18 - .../Solution/TrieSection/DayQuestion.cs | 44 --- cSharp-source/Solution/TrieSection/Program.cs | 1 - .../Solution/TrieSection/TrieSection.csproj | 10 - 36 files changed, 75 insertions(+), 1271 deletions(-) delete mode 100644 cSharp-source/Solution/AlgorithmTest/AlgorithmTest.csproj delete mode 100644 cSharp-source/Solution/AlgorithmTest/ArrayTest.cs delete mode 100644 cSharp-source/Solution/AlgorithmTest/Usings.cs delete mode 100644 cSharp-source/Solution/ArraySection/ArraySection.csproj delete mode 100644 cSharp-source/Solution/ArraySection/DayQuestion.cs delete mode 100644 cSharp-source/Solution/ArraySection/GlobalUsings.cs delete mode 100644 cSharp-source/Solution/ArraySection/Matrix.cs delete mode 100644 cSharp-source/Solution/ArraySection/Program.cs delete mode 100644 cSharp-source/Solution/DPSection/DPSection.csproj delete mode 100644 cSharp-source/Solution/DPSection/DayQuestion.cs delete mode 100644 cSharp-source/Solution/DPSection/Program.cs delete mode 100644 cSharp-source/Solution/EncodeSection/DayQuestion.cs delete mode 100644 cSharp-source/Solution/EncodeSection/EncodeSection.csproj delete mode 100644 cSharp-source/Solution/LinkSection/LinkRemove.cs delete mode 100644 cSharp-source/Solution/LinkSection/LinkSection.csproj delete mode 100644 cSharp-source/Solution/LinkSection/ListNode.cs delete mode 100644 cSharp-source/Solution/LinkSection/Program.cs delete mode 100644 cSharp-source/Solution/OrderSetSection/MyClendarTwo.cs delete mode 100644 cSharp-source/Solution/OrderSetSection/OrderSetSection.csproj delete mode 100644 cSharp-source/Solution/OrderSetSection/Program.cs delete mode 100644 cSharp-source/Solution/OrderSetSection/SkipList.cs delete mode 100644 cSharp-source/Solution/QueueSection/DayQuestion.cs delete mode 100644 cSharp-source/Solution/QueueSection/Program.cs delete mode 100644 cSharp-source/Solution/QueueSection/QueueSection.csproj delete mode 100644 cSharp-source/Solution/StackSection/DayQuestions.cs delete mode 100644 cSharp-source/Solution/StackSection/Program.cs delete mode 100644 cSharp-source/Solution/StackSection/StackSection.csproj delete mode 100644 cSharp-source/Solution/TreeSection/DayQuestion.cs delete mode 100644 cSharp-source/Solution/TreeSection/FindTreeNode.cs delete mode 100644 cSharp-source/Solution/TreeSection/Program.cs delete mode 100644 cSharp-source/Solution/TreeSection/TreeNode.cs delete mode 100644 cSharp-source/Solution/TreeSection/TreeSection.csproj delete mode 100644 cSharp-source/Solution/TrieSection/DayQuestion.cs delete mode 100644 cSharp-source/Solution/TrieSection/Program.cs delete mode 100644 cSharp-source/Solution/TrieSection/TrieSection.csproj diff --git a/cSharp-source/Solution/AlgorithmTest/AlgorithmTest.csproj b/cSharp-source/Solution/AlgorithmTest/AlgorithmTest.csproj deleted file mode 100644 index 77fc367..0000000 --- a/cSharp-source/Solution/AlgorithmTest/AlgorithmTest.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - net6.0 - enable - enable - - false - - TestSolution - - - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - - - - - - diff --git a/cSharp-source/Solution/AlgorithmTest/ArrayTest.cs b/cSharp-source/Solution/AlgorithmTest/ArrayTest.cs deleted file mode 100644 index dbab50c..0000000 --- a/cSharp-source/Solution/AlgorithmTest/ArrayTest.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace AlgorithmTest; - -public class ArrayTest -{ - [Fact] - public void Test() - { - var invoker = new DayQuestion(); - } -} \ No newline at end of file diff --git a/cSharp-source/Solution/AlgorithmTest/Usings.cs b/cSharp-source/Solution/AlgorithmTest/Usings.cs deleted file mode 100644 index 8e27833..0000000 --- a/cSharp-source/Solution/AlgorithmTest/Usings.cs +++ /dev/null @@ -1,2 +0,0 @@ -global using Xunit; -global using ArraySection; \ No newline at end of file diff --git a/cSharp-source/Solution/ArraySection/ArraySection.csproj b/cSharp-source/Solution/ArraySection/ArraySection.csproj deleted file mode 100644 index b9de063..0000000 --- a/cSharp-source/Solution/ArraySection/ArraySection.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - - Exe - net6.0 - enable - enable - - - diff --git a/cSharp-source/Solution/ArraySection/DayQuestion.cs b/cSharp-source/Solution/ArraySection/DayQuestion.cs deleted file mode 100644 index 2e41a15..0000000 --- a/cSharp-source/Solution/ArraySection/DayQuestion.cs +++ /dev/null @@ -1,342 +0,0 @@ -namespace ArraySection; - -public class DayQuestion -{ - #region day 6.16 - - // Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. - // - // A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: - // 0 <= i, j < nums.length - // i != j - // nums[i] - nums[j] == k - // Notice that |val| denotes the absolute value of val. - - // Example 1: - // Input: nums = [3,1,4,1,5], k = 2 - // Output: 2 - // Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). - // Although we have two 1s in the input, we should only return the number of unique pairs. - - // Example 2: - // Input: nums = [1,2,3,4,5], k = 1 - // Output: 4 - // Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). - - // Example 3: - // Input: nums = [1,3,1,5,4], k = 0 - // Output: 1 - // Explanation: There is one 0-diff pair in the array, (1, 1). - - public int FindPairs(int[] nums, int k) - { - if (k < 0) return 0; - var dic = new Dictionary(nums.Length); - foreach (var num in nums) - { - if (!dic.ContainsKey(num)) - dic[num] = 0; - dic[num]++; - } - - // 返回数量大于1的 - return k == 0 ? dic.Count(x => x.Value > 1) : dic.Count(item => dic.ContainsKey(item.Key + k)); - } - - #endregion - - #region day 6.17 - - // Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right. - // Note that elements beyond the length of the original array are not written. - // Do the above modifications to the input array in place and do not return anything. - - // Example 1: - // - // Input: arr = [1,0,2,3,0,4,5,0] - // Output: [1,0,0,2,3,0,0,4] - // Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4] - - public void DuplicateZeros(int[] arr) - { - var ans = new List(); - var cursor = 0; - - while (ans.Count < arr.Length) - { - if (arr[cursor] == 0) ans.Add(arr[cursor]); - ans.Add(arr[cursor]); - cursor++; - } - - if (ans.Count > arr.Length) ans.RemoveAt(ans.Count - 1); - - ans.CopyTo(arr, 0); - } - - public void DuplicateZerosV2(int[] arr) - { - var start = 0; - var end = arr.Length; - var index = -1; - - while (start < end) - { - index++; - if (arr[index] != 0) start++; - else start += 2; - } - - var point = end - 1; - if (start == end + 1) - { - arr[point] = 0; - index--; - point--; - } - - while (point >= 0) - { - arr[point--] = arr[index]; - if (arr[index] == 0) - arr[point--] = 0; - index--; - } - } - - #endregion - - #region day 6.21 - - // Given a valid (IPv4) IP address, return a defanged version of that IP address. - // Example 1: - // Input: address = "1.1.1.1" - // Output: "1[.]1[.]1[.]1" - public string DefangIPaddr(string address) - { - var chars = address.ToCharArray(); - var sb = new StringBuilder(); - foreach (var t in chars) - { - if (t == '.') sb.Append('['); - sb.Append(t); - if (t == '.') sb.Append(']'); - } - return sb.ToString(); - } - - #endregion - - #region day 6.23 - - // 30. Substring with Concatenation of All Words - // You are given a string s and an array of strings words of the same length. - // Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, - // in any order, and without any intervening characters. - // You can return the answer in any order. - - //Input: s = "barfoothefoobarman", words = ["foo","bar"] - //Output: [0,9] - //Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively. - //The output order does not matter, returning[9, 0] is fine too. - - public IList FindSubstring(string s, string[] words) - { - IList res = new List(); - int m = words.Length, n = words[0].Length, ls = s.Length; - for (int i = 0; i < n; i++) - { - if (i + m * n > ls) - { - break; - } - Dictionary differ = new Dictionary(); - for (int j = 0; j < m; j++) - { - string word = s.Substring(i + j * n, n); - if (!differ.ContainsKey(word)) - { - differ.Add(word, 0); - } - differ[word]++; - } - foreach (string word in words) - { - if (!differ.ContainsKey(word)) - { - differ.Add(word, 0); - } - differ[word]--; - if (differ[word] == 0) - { - differ.Remove(word); - } - } - for (int start = i; start < ls - m * n + 1; start += n) - { - if (start != i) - { - string word = s.Substring(start + (m - 1) * n, n); - if (!differ.ContainsKey(word)) - { - differ.Add(word, 0); - } - differ[word]++; - if (differ[word] == 0) - { - differ.Remove(word); - } - word = s.Substring(start - n, n); - if (!differ.ContainsKey(word)) - { - differ.Add(word, 0); - } - differ[word]--; - if (differ[word] == 0) - { - differ.Remove(word); - } - } - if (differ.Count == 0) - { - res.Add(start); - } - } - } - return res; - } - - #endregion - - #region day 6.28 - - // 324. Wiggle Sort II - //Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3] > nums[4]... - //You may assume the input array always has a valid answer. - - //Example 1: - //Input: nums = [1,5,1,1,6,4] - //Output: [1,6,1,5,1,4] - //Explanation: [1,4,1,5,1,6] is also accepted. - - //Example 2: - //Input: nums = [1, 3, 2, 2, 3, 1] - //Output: [2,3,1,3,1,2] - - public void WiggleSort(int[] nums) - { - Array.Sort(nums); - var st1 = new Stack(); - var st2 = new Stack(); - int half = (nums.Length - 1) / 2, idx = 0; - while (idx <= half) - { - st1.Push(nums[idx++]); - } - while (idx < nums.Length) - { - st2.Push(nums[idx++]); - } - bool flag = true; - idx = 0; - while (st1.Count > 0 || st2.Count > 0) - { - nums[idx++] = flag ? st1.Pop() : st2.Pop(); - flag = !flag; - } - } - - #endregion - - #region day 7.8 - - public int MinCostToMoveChips(int[] position) - { - int len = position.Length, ans = int.MaxValue; - for (int i = 0; i < len; i++) - { - int a = position[i], cur = 0; - for (int j = 0; j < len; j++) - { - int b = position[j]; - cur += Math.Abs(a - b) % 2; - } - ans = Math.Min(ans, cur); - } - return ans; - } - - #endregion - - #region day 7.18 - - // 565. Array Nesting - public int ArrayNesting(int[] nums) - { - int res = 1; - bool[] visited = new bool[nums.Length]; - - for (int i = 0; i < nums.Length; i++) - { - // 乱序超过一半,则全为乱序了 - if (res > nums.Length / 2) - return res; - // 若该访问点被某序列访问过,那么以这个元素为头的序列肯定不为最长 - if (visited[nums[i]] == true) - continue; - - int len = 1; - int next = nums[nums[i]]; - while (next != nums[i]) - { - visited[next] = true; - - len++; - next = nums[next]; - } - res = len > res ? len : res; - } - return res; - } - - #endregion - - #region day 7.22 - - //757. Set Intersection Size At Least Two - //An integer interval[a, b] (for integers a o1[0] == o2[0] ? o2[1].CompareTo(o1[1]) : o1[0].CompareTo(o2[0])); - var n = intervals.Length; - - var cur = intervals[n - 1][0]; - var next = intervals[n - 1][0] + 1; - var ans = 2; - - for (int i = n - 2; i >= 0; i--) - { - if (intervals[i][1] >= next) continue; - else if (intervals[i][1] < cur) - { - cur = intervals[i][0]; - next = intervals[i][0] + 1; - ans += 2; - } - else - { - next = cur; - cur = intervals[i][0]; - ans++; - } - } - return ans; - } - - #endregion -} \ No newline at end of file diff --git a/cSharp-source/Solution/ArraySection/GlobalUsings.cs b/cSharp-source/Solution/ArraySection/GlobalUsings.cs deleted file mode 100644 index ad56d1b..0000000 --- a/cSharp-source/Solution/ArraySection/GlobalUsings.cs +++ /dev/null @@ -1,2 +0,0 @@ -global using System.Text; -global using System.Diagnostics.CodeAnalysis; diff --git a/cSharp-source/Solution/ArraySection/Matrix.cs b/cSharp-source/Solution/ArraySection/Matrix.cs deleted file mode 100644 index d975ea6..0000000 --- a/cSharp-source/Solution/ArraySection/Matrix.cs +++ /dev/null @@ -1,144 +0,0 @@ -namespace ArraySection; - -public class Matrix -{ - #region 59 - - // 59. Spiral Matrix II - // Given a positive integer n, generate an n x n matrix filled with elements - // from 1 to n2 in spiral order. - - // Input: n = 3 - // Output: [[1,2,3],[8,9,4],[7,6,5]] - // - // Input: n = 1 - // Output: [[1]] - - public int[][] GenerateMatrix(int n) - { - // Init array - var matrix = new int[n][]; - for (var i = 0; i < n; i++) - { - matrix[i] = new int[n]; - } - - var left = 0; - var right = n - 1; - var top = 0; - var bottom = n - 1; - var start = 1; - var end = n * n; - - // start rotate - while (start <= end) - { - for (int i = left; i <= right; i++) - { - matrix[top][i] = start; - start++; - } - - top++; - - for (int i = top; i <= bottom; i++) - { - matrix[i][right] = start; - start++; - } - - right--; - - for (int i = right; i >= left; i--) - { - matrix[bottom][i] = start; - start++; - } - - bottom--; - - for (int i = bottom; i >= top; i--) - { - matrix[i][left] = start; - start++; - } - - left++; - } - - return matrix; - } - - #endregion - - #region 1257 - - // 1252. Cells with Odd Values in a Matrix - - // There is an m x n matrix that is initialized to all 0's. - // There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix. - // For each location indices[i], do both of the following: - - // Increment all the cells on row ri. - // Increment all the cells on column ci. - // Given m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices. - - [SuppressMessage("ReSharper", "AssignmentInConditionalExpression")] - public int OddCells(int m, int n, int[][] indices) - { - var row = new int[m]; - var col = new int[n]; - - foreach (var index in indices) - { - row[index[0]]++; - col[index[1]]++; - } - - int oddRow = row.Count(r => (r & 1) == 0); - int oddCol = col.Count(c => (c & 1) == 0); - - return (oddRow * n) + (oddCol * m) - 2 * (oddCol * oddRow); - } - - #endregion - - #region 1260 - - //Given a 2D grid of size m x n and an integer k.You need to shift the grid k times. - - //In one shift operation: - //Element at grid[i][j] moves to grid[i][j + 1]. - //Element at grid[i][n - 1] moves to grid[i + 1][0]. - //Element at grid[m - 1][n - 1] moves to grid[0][0]. - //Return the 2D grid after applying shift operation k times. - - public IList> ShiftGrid(int[][] grid, int k) - { - int[] nums = new int[grid[0].Length * grid.Length]; - - foreach (var row in grid) - { - foreach (var num in row) - { - k %= nums.Length; - nums[k++] = num; - } - } - - IList> result = new List>(nums.Length); - k = 0; - for (int i = 0; i < grid.Length; i++) - { - var tempList = new List(grid[0].Length); - for (int j = 0; j < grid[0].Length; j++) - { - tempList.Add(nums[k++]); - } - result.Add(tempList); - } - return result; - } - - #endregion -} \ No newline at end of file diff --git a/cSharp-source/Solution/ArraySection/Program.cs b/cSharp-source/Solution/ArraySection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/ArraySection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/DPSection/DPSection.csproj b/cSharp-source/Solution/DPSection/DPSection.csproj deleted file mode 100644 index 74abf5c..0000000 --- a/cSharp-source/Solution/DPSection/DPSection.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - - Exe - net6.0 - enable - enable - - - diff --git a/cSharp-source/Solution/DPSection/DayQuestion.cs b/cSharp-source/Solution/DPSection/DayQuestion.cs deleted file mode 100644 index 6d11dbd..0000000 --- a/cSharp-source/Solution/DPSection/DayQuestion.cs +++ /dev/null @@ -1,98 +0,0 @@ -namespace DPSection; - -public class DayQuestion -{ - #region day 6.25 - - //假如有一排房子,共 n 个,每个房子可以被粉刷成红色、蓝色或者绿色这三种颜色中的一种,你需要粉刷所有的房子并且使其相邻的两个房子颜色不能相同。 - //当然,因为市场上不同颜色油漆的价格不同,所以房子粉刷成不同颜色的花费成本也是不同的。每个房子粉刷成不同颜色的花费是以一个 n x 3 的正整数矩阵 costs 来表示的。 - //例如,costs[0][0] 表示第 0 号房子粉刷成红色的成本花费;costs[1][2] 表示第 1 号房子粉刷成绿色的花费,以此类推。 - //请计算出粉刷完所有房子最少的花费成本。 - - //示例 1: - //输入: costs = [[17,2,17],[16,16,5],[14,3,19]] - //输出: 10 - //解释: 将 0 号房子粉刷成蓝色,1 号房子粉刷成绿色,2 号房子粉刷成蓝色。 最少花费: 2 + 5 + 3 = 10。 - - //示例 2: - //输入: costs = [[7,6,2]] - //输出: 2 - - public int MinCost(int[][] costs) - { - var size = costs.Length; - int a = costs[0][0], b = costs[0][1], c = costs[0][2]; - for (int i = 1; i < size; i++) - { - // 由其他的两种不同颜色决定 - int d = Math.Min(b, c) + costs[i][0]; - int e = Math.Min(a, c) + costs[i][1]; - int f = Math.Min(a, b) + costs[i][2]; - a = d; b = e; c = f; - } - return Math.Min(a, Math.Min(b, c)); - } - - #endregion - - #region day 6.27 - - // Given an array of strings strs, return the length of the longest uncommon subsequence between them. - // If the longest uncommon subsequence does not exist, return -1. - // An uncommon subsequence between an array of strings is a string that is a subsequence of one string - // but not the others. - - // Example 1: - // Input: strs = ["aba","cdc","eae"] - // Output: 3 - - // Example 2: - // Input: strs = ["aaa","aaa","aa"] - // Output: -1 - - public int FindLUSlength(string[] strs) - { - int n = strs.Length; - int res = -1; - - for (int i = 0; i < n; i++) - { - if (strs[i].Length <= res) continue; - bool notSame = true; - for (int j = 0; j < n && notSame; j++) - { - if (i == j) continue; - if (Check(strs[i], strs[j])) notSame = false; - } - if (notSame) res = strs[i].Length; - } - return res; - } - - private bool Check(string s1, string s2) - { - int n = s1.Length, m = s2.Length; - if (m < n) return false; - - int[][] f = new int[n + 1][]; - for (int i = 0; i < n + 1; i++) - f[i] = new int[m + 1]; - - for (int i = 1; i <= n; i++) - { - for (int j = 1; j <= m; j++) - { - if (s1[i - 1] == s2[j - 1]) - f[i][j] = f[i - 1][j - 1] + 1; - else - f[i][j] = f[i - 1][j - 1]; - - f[i][j] = Math.Max(f[i][j], Math.Max(f[i][j - 1], f[i - 1][j])); - if (f[i][j] == n) return true; - } - } - return false; - } - - #endregion -} diff --git a/cSharp-source/Solution/DPSection/Program.cs b/cSharp-source/Solution/DPSection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/DPSection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/EncodeSection/DayQuestion.cs b/cSharp-source/Solution/EncodeSection/DayQuestion.cs deleted file mode 100644 index 0581947..0000000 --- a/cSharp-source/Solution/EncodeSection/DayQuestion.cs +++ /dev/null @@ -1,49 +0,0 @@ -namespace EncodeSection; - -public class DayQuestion -{ - #region Day 6.29 - - // 535. Encode and Decode TinyURL - // TinyURL is a URL shortening service where you enter a URL such as - // https:leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. - // Design a class to encode a URL and decode a tiny URL. - // There is no restriction on how your encode/decode algorithm should work. - // You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. - - // Base62 - private Dictionary _tiny2Origin = new Dictionary(); - private Dictionary _origin2Tiny = new Dictionary(); - private const string _codeStr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; - private const string _prefix = "https://xieyi.com/tiny/"; - private const int _k = 6; - - public string OriginEncode(string longUrl) - { - var random = new Random(); - while (!_origin2Tiny.ContainsKey(longUrl)) - { - // generate keys - var keys = new char[_k]; - for (var i = 0; i < _k; i++) keys[i] = _codeStr[random.Next(_codeStr.Length)]; - - var redirect = _prefix + keys.ToString(); - if (_tiny2Origin.ContainsKey(redirect)) continue; - - _tiny2Origin.Add(redirect, longUrl); - _origin2Tiny.Add(longUrl, redirect); - } - - return _origin2Tiny[longUrl]; - } - - public string TinyDecode(string shortUrl) => _tiny2Origin[shortUrl]; - - #endregion - - #region Day 7.14 - - - - #endregion -} \ No newline at end of file diff --git a/cSharp-source/Solution/EncodeSection/EncodeSection.csproj b/cSharp-source/Solution/EncodeSection/EncodeSection.csproj deleted file mode 100644 index 6afd605..0000000 --- a/cSharp-source/Solution/EncodeSection/EncodeSection.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - - net6.0 - enable - enable - EncodeSolution - - - diff --git a/cSharp-source/Solution/LinkSection/LinkRemove.cs b/cSharp-source/Solution/LinkSection/LinkRemove.cs deleted file mode 100644 index 4d534a5..0000000 --- a/cSharp-source/Solution/LinkSection/LinkRemove.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace LinkSection; - -public class LinkRemove -{ - public ListNode RemoveElements(ListNode head, int val) - { - var dummyLink = new ListNode(); - dummyLink.next = head; - var cur = dummyLink; - - while (cur?.next != null) - { - if (cur.next.val == val) - cur.next = cur.next.next; - else - cur = cur.next; - } - return dummyLink.next; - } -} \ No newline at end of file diff --git a/cSharp-source/Solution/LinkSection/LinkSection.csproj b/cSharp-source/Solution/LinkSection/LinkSection.csproj deleted file mode 100644 index b9de063..0000000 --- a/cSharp-source/Solution/LinkSection/LinkSection.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - - Exe - net6.0 - enable - enable - - - diff --git a/cSharp-source/Solution/LinkSection/ListNode.cs b/cSharp-source/Solution/LinkSection/ListNode.cs deleted file mode 100644 index a428592..0000000 --- a/cSharp-source/Solution/LinkSection/ListNode.cs +++ /dev/null @@ -1,15 +0,0 @@ -// ReSharper disable All -#pragma warning disable CS8625 - -namespace LinkSection; - -public class ListNode -{ - public int val; - public ListNode next; - public ListNode(int val = 0, ListNode next = null) - { - this.val = val; - this.next = next; - } -} diff --git a/cSharp-source/Solution/LinkSection/Program.cs b/cSharp-source/Solution/LinkSection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/LinkSection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/OrderSetSection/MyClendarTwo.cs b/cSharp-source/Solution/OrderSetSection/MyClendarTwo.cs deleted file mode 100644 index b29b2e1..0000000 --- a/cSharp-source/Solution/OrderSetSection/MyClendarTwo.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OrderSetSection; - -public class MyCalendarTwo -{ - private SortedDictionary calendar; - - public MyCalendarTwo() - { - calendar = new SortedDictionary(); - } - - public bool Book(int start, int end) - { - int res = 0, maxBook = 0; - - if (!calendar.TryAdd(start, 1)) calendar[start] += 1; - if (!calendar.TryAdd(end, -1)) calendar[end] -= 1; - - foreach (var item in calendar) - { - maxBook += item.Value; - res = Math.Max(maxBook, res); - if (maxBook > 2) - { - calendar[start] -= 1; - calendar[end] += 1; - return false; - } - } - - return true; - } -} diff --git a/cSharp-source/Solution/OrderSetSection/OrderSetSection.csproj b/cSharp-source/Solution/OrderSetSection/OrderSetSection.csproj deleted file mode 100644 index 74abf5c..0000000 --- a/cSharp-source/Solution/OrderSetSection/OrderSetSection.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - - Exe - net6.0 - enable - enable - - - diff --git a/cSharp-source/Solution/OrderSetSection/Program.cs b/cSharp-source/Solution/OrderSetSection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/OrderSetSection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/OrderSetSection/SkipList.cs b/cSharp-source/Solution/OrderSetSection/SkipList.cs deleted file mode 100644 index 041d19e..0000000 --- a/cSharp-source/Solution/OrderSetSection/SkipList.cs +++ /dev/null @@ -1,67 +0,0 @@ -namespace OrderSetSection; - -public class SkipList -{ - private const int level = 10; - private Random _random = new Random(); - - class Node - { - public int val { get; set; } - public Node[] ne { get; set; } = new Node[level]; - - public Node(int _val) - { - val = _val; - } - } - - private Node se = new Node(-1); - - - /// - /// 查找出每一层比 target 严格小的最后一个节点,将其存成 ns 数组。 - /// 即 ns[i] 为 level=i 层严格比 target 小的最后一个节点。 - /// - /// - /// - void Find(int target, Node[] ns) - { - Node cur = se; - for (int i = level - 1; i >= 0; i--) - { - while (cur.ne[i] != null && cur.ne[i].val < target) cur = cur.ne[i]; - ns[i] = cur; // 找到大于target的链表层 - } - } - - public bool Search(int t) - { - Node[] ns = new Node[level]; - Find(t, ns); - return ns[0].ne[0] != null && ns[0].ne[0].val == t; - } - - public void Add(int t) - { - Node[] ns = new Node[level]; - Find(t, ns); - Node node = new Node(t); - for (int i = 0; i < level; i++) - { - node.ne[i] = ns[i].ne[i]; - ns[i].ne[i] = node; - if (_random.Next(2) == 0) break; - } - } - - public Boolean Erase(int t) - { - Node[] ns = new Node[level]; - Find(t, ns); - Node node = ns[0].ne[0]; - if (node == null || node.val != t) return false; - for (int i = 0; i < level && ns[i].ne[i] == node; i++) ns[i].ne[i] = ns[i].ne[i].ne[i]; - return true; - } -} \ No newline at end of file diff --git a/cSharp-source/Solution/QueueSection/DayQuestion.cs b/cSharp-source/Solution/QueueSection/DayQuestion.cs deleted file mode 100644 index 34c0c03..0000000 --- a/cSharp-source/Solution/QueueSection/DayQuestion.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace QueueSection; - -public class DayQuestion -{ -} - -// 剑指 Offer II 041. 滑动窗口的平均值 -public class MovingAverage -{ - private int[] arr; - private int _size, sum, rear, front; - - /** Initialize your data structure here. */ - public MovingAverage(int size) - { - this.arr = new int [10010]; - this._size = size; - } - - public double Next(int val) - { - sum += arr[rear++] = val; - if (rear - front > _size) - { - sum -= arr[front]; - front++; - } - return (double)sum / (rear - front); - } -} \ No newline at end of file diff --git a/cSharp-source/Solution/QueueSection/Program.cs b/cSharp-source/Solution/QueueSection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/QueueSection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/QueueSection/QueueSection.csproj b/cSharp-source/Solution/QueueSection/QueueSection.csproj deleted file mode 100644 index b9de063..0000000 --- a/cSharp-source/Solution/QueueSection/QueueSection.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - - Exe - net6.0 - enable - enable - - - diff --git a/cSharp-source/Solution/Solution.sln b/cSharp-source/Solution/Solution.sln index 8429c6b..f28aefd 100644 --- a/cSharp-source/Solution/Solution.sln +++ b/cSharp-source/Solution/Solution.sln @@ -3,34 +3,38 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.2.32616.157 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ArraySection", "ArraySection\ArraySection.csproj", "{F1BDFC33-95C2-48D4-8A36-3476BCE8DF87}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "0-Test", "0-Test", "{06382AED-685A-4336-B553-DDA7C3A8C616}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AlgorithmTest", "AlgorithmTest\AlgorithmTest.csproj", "{897AB4BA-47B7-4AAE-9003-7FA7E6B6E51D}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "1-Basic", "1-Basic", "{9CFDC530-AE9D-4259-BB7D-4DC862F51C2E}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LinkSection", "LinkSection\LinkSection.csproj", "{B7608955-BC27-45FA-824E-EC3500CBB69F}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "2-External", "2-External", "{5D2E938C-2618-4DD9-A439-F193655266A0}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TreeSection", "TreeSection\TreeSection.csproj", "{D3B21535-A822-4005-A2DA-9F236EF19C43}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{4A4A64FA-723A-48CE-960C-CE3E0E60F364}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + EndProjectSection EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DPSection", "DPSection\DPSection.csproj", "{CE4BAB7B-6825-4927-A48A-28DEB8E80B47}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AlgorithmTest", "0-Test\AlgorithmTest\AlgorithmTest.csproj", "{6341CEA4-1D22-4330-984A-28C5C9F1A102}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EncodeSection", "EncodeSection\EncodeSection.csproj", "{5D630232-7215-4FCF-A5DA-7B943B61BD58}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArraySection", "1-Basic\ArraySection\ArraySection.csproj", "{94FD5CF4-A049-45FD-ADBC-15DDBE88A796}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "0-Test", "0-Test", "{06382AED-685A-4336-B553-DDA7C3A8C616}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LinkSection", "1-Basic\LinkSection\LinkSection.csproj", "{1423494B-2F5D-481D-AA50-1F2D965394DE}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "1-Basic", "1-Basic", "{9CFDC530-AE9D-4259-BB7D-4DC862F51C2E}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QueueSection", "1-Basic\QueueSection\QueueSection.csproj", "{9DB66097-4D62-4E8F-8531-3F44FB8B91D2}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "2-External", "2-External", "{5D2E938C-2618-4DD9-A439-F193655266A0}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StackSection", "1-Basic\StackSection\StackSection.csproj", "{26C5CAF2-FDFD-48C4-97C8-1214AC963D8D}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TrieSection", "TrieSection\TrieSection.csproj", "{6F24B5FF-4F1A-4E65-9959-118DAA01C460}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StringSection", "1-Basic\StringSection\StringSection.csproj", "{AF63F2C5-34DC-4E7B-8B79-C6F3D7A0482D}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QueueSection", "QueueSection\QueueSection.csproj", "{1F97AF7C-41C2-48D5-88E1-2DF39E236D50}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TreeSection", "1-Basic\TreeSection\TreeSection.csproj", "{E8F30DCA-D2B4-41DC-8AB0-54A70EFC90DE}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OrderSetSection", "OrderSetSection\OrderSetSection.csproj", "{96EBA533-AA18-440E-A1A0-37ED75FDBE94}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DPSection", "2-External\DPSection\DPSection.csproj", "{C8DEE532-AAAA-40FC-962E-F21DAA6C8C6F}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{4A4A64FA-723A-48CE-960C-CE3E0E60F364}" - ProjectSection(SolutionItems) = preProject - .editorconfig = .editorconfig - EndProjectSection +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EncodeSection", "2-External\EncodeSection\EncodeSection.csproj", "{F001E030-28DE-4C40-B424-C9B50100FEC7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OrderSetSection", "2-External\OrderSetSection\OrderSetSection.csproj", "{35FD5694-B1B8-4FD5-8FA8-896243F99EAB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrieSection", "2-External\TrieSection\TrieSection.csproj", "{95F18BB5-F085-4CE2-86DC-2322CFF768A2}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -38,56 +42,66 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {F1BDFC33-95C2-48D4-8A36-3476BCE8DF87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F1BDFC33-95C2-48D4-8A36-3476BCE8DF87}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F1BDFC33-95C2-48D4-8A36-3476BCE8DF87}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F1BDFC33-95C2-48D4-8A36-3476BCE8DF87}.Release|Any CPU.Build.0 = Release|Any CPU - {897AB4BA-47B7-4AAE-9003-7FA7E6B6E51D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {897AB4BA-47B7-4AAE-9003-7FA7E6B6E51D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {897AB4BA-47B7-4AAE-9003-7FA7E6B6E51D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {897AB4BA-47B7-4AAE-9003-7FA7E6B6E51D}.Release|Any CPU.Build.0 = Release|Any CPU - {B7608955-BC27-45FA-824E-EC3500CBB69F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B7608955-BC27-45FA-824E-EC3500CBB69F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B7608955-BC27-45FA-824E-EC3500CBB69F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B7608955-BC27-45FA-824E-EC3500CBB69F}.Release|Any CPU.Build.0 = Release|Any CPU - {D3B21535-A822-4005-A2DA-9F236EF19C43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D3B21535-A822-4005-A2DA-9F236EF19C43}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D3B21535-A822-4005-A2DA-9F236EF19C43}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D3B21535-A822-4005-A2DA-9F236EF19C43}.Release|Any CPU.Build.0 = Release|Any CPU - {CE4BAB7B-6825-4927-A48A-28DEB8E80B47}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CE4BAB7B-6825-4927-A48A-28DEB8E80B47}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CE4BAB7B-6825-4927-A48A-28DEB8E80B47}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CE4BAB7B-6825-4927-A48A-28DEB8E80B47}.Release|Any CPU.Build.0 = Release|Any CPU - {5D630232-7215-4FCF-A5DA-7B943B61BD58}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5D630232-7215-4FCF-A5DA-7B943B61BD58}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5D630232-7215-4FCF-A5DA-7B943B61BD58}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5D630232-7215-4FCF-A5DA-7B943B61BD58}.Release|Any CPU.Build.0 = Release|Any CPU - {6F24B5FF-4F1A-4E65-9959-118DAA01C460}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6F24B5FF-4F1A-4E65-9959-118DAA01C460}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6F24B5FF-4F1A-4E65-9959-118DAA01C460}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6F24B5FF-4F1A-4E65-9959-118DAA01C460}.Release|Any CPU.Build.0 = Release|Any CPU - {1F97AF7C-41C2-48D5-88E1-2DF39E236D50}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1F97AF7C-41C2-48D5-88E1-2DF39E236D50}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1F97AF7C-41C2-48D5-88E1-2DF39E236D50}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1F97AF7C-41C2-48D5-88E1-2DF39E236D50}.Release|Any CPU.Build.0 = Release|Any CPU - {96EBA533-AA18-440E-A1A0-37ED75FDBE94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {96EBA533-AA18-440E-A1A0-37ED75FDBE94}.Debug|Any CPU.Build.0 = Debug|Any CPU - {96EBA533-AA18-440E-A1A0-37ED75FDBE94}.Release|Any CPU.ActiveCfg = Release|Any CPU - {96EBA533-AA18-440E-A1A0-37ED75FDBE94}.Release|Any CPU.Build.0 = Release|Any CPU + {6341CEA4-1D22-4330-984A-28C5C9F1A102}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6341CEA4-1D22-4330-984A-28C5C9F1A102}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6341CEA4-1D22-4330-984A-28C5C9F1A102}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6341CEA4-1D22-4330-984A-28C5C9F1A102}.Release|Any CPU.Build.0 = Release|Any CPU + {94FD5CF4-A049-45FD-ADBC-15DDBE88A796}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {94FD5CF4-A049-45FD-ADBC-15DDBE88A796}.Debug|Any CPU.Build.0 = Debug|Any CPU + {94FD5CF4-A049-45FD-ADBC-15DDBE88A796}.Release|Any CPU.ActiveCfg = Release|Any CPU + {94FD5CF4-A049-45FD-ADBC-15DDBE88A796}.Release|Any CPU.Build.0 = Release|Any CPU + {1423494B-2F5D-481D-AA50-1F2D965394DE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1423494B-2F5D-481D-AA50-1F2D965394DE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1423494B-2F5D-481D-AA50-1F2D965394DE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1423494B-2F5D-481D-AA50-1F2D965394DE}.Release|Any CPU.Build.0 = Release|Any CPU + {9DB66097-4D62-4E8F-8531-3F44FB8B91D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9DB66097-4D62-4E8F-8531-3F44FB8B91D2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9DB66097-4D62-4E8F-8531-3F44FB8B91D2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9DB66097-4D62-4E8F-8531-3F44FB8B91D2}.Release|Any CPU.Build.0 = Release|Any CPU + {26C5CAF2-FDFD-48C4-97C8-1214AC963D8D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {26C5CAF2-FDFD-48C4-97C8-1214AC963D8D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {26C5CAF2-FDFD-48C4-97C8-1214AC963D8D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {26C5CAF2-FDFD-48C4-97C8-1214AC963D8D}.Release|Any CPU.Build.0 = Release|Any CPU + {AF63F2C5-34DC-4E7B-8B79-C6F3D7A0482D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AF63F2C5-34DC-4E7B-8B79-C6F3D7A0482D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AF63F2C5-34DC-4E7B-8B79-C6F3D7A0482D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AF63F2C5-34DC-4E7B-8B79-C6F3D7A0482D}.Release|Any CPU.Build.0 = Release|Any CPU + {E8F30DCA-D2B4-41DC-8AB0-54A70EFC90DE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E8F30DCA-D2B4-41DC-8AB0-54A70EFC90DE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E8F30DCA-D2B4-41DC-8AB0-54A70EFC90DE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E8F30DCA-D2B4-41DC-8AB0-54A70EFC90DE}.Release|Any CPU.Build.0 = Release|Any CPU + {C8DEE532-AAAA-40FC-962E-F21DAA6C8C6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C8DEE532-AAAA-40FC-962E-F21DAA6C8C6F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C8DEE532-AAAA-40FC-962E-F21DAA6C8C6F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C8DEE532-AAAA-40FC-962E-F21DAA6C8C6F}.Release|Any CPU.Build.0 = Release|Any CPU + {F001E030-28DE-4C40-B424-C9B50100FEC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F001E030-28DE-4C40-B424-C9B50100FEC7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F001E030-28DE-4C40-B424-C9B50100FEC7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F001E030-28DE-4C40-B424-C9B50100FEC7}.Release|Any CPU.Build.0 = Release|Any CPU + {35FD5694-B1B8-4FD5-8FA8-896243F99EAB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {35FD5694-B1B8-4FD5-8FA8-896243F99EAB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {35FD5694-B1B8-4FD5-8FA8-896243F99EAB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {35FD5694-B1B8-4FD5-8FA8-896243F99EAB}.Release|Any CPU.Build.0 = Release|Any CPU + {95F18BB5-F085-4CE2-86DC-2322CFF768A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {95F18BB5-F085-4CE2-86DC-2322CFF768A2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {95F18BB5-F085-4CE2-86DC-2322CFF768A2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {95F18BB5-F085-4CE2-86DC-2322CFF768A2}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution - {F1BDFC33-95C2-48D4-8A36-3476BCE8DF87} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} - {897AB4BA-47B7-4AAE-9003-7FA7E6B6E51D} = {06382AED-685A-4336-B553-DDA7C3A8C616} - {B7608955-BC27-45FA-824E-EC3500CBB69F} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} - {D3B21535-A822-4005-A2DA-9F236EF19C43} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} - {CE4BAB7B-6825-4927-A48A-28DEB8E80B47} = {5D2E938C-2618-4DD9-A439-F193655266A0} - {5D630232-7215-4FCF-A5DA-7B943B61BD58} = {5D2E938C-2618-4DD9-A439-F193655266A0} - {6F24B5FF-4F1A-4E65-9959-118DAA01C460} = {5D2E938C-2618-4DD9-A439-F193655266A0} - {1F97AF7C-41C2-48D5-88E1-2DF39E236D50} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} - {96EBA533-AA18-440E-A1A0-37ED75FDBE94} = {5D2E938C-2618-4DD9-A439-F193655266A0} + {6341CEA4-1D22-4330-984A-28C5C9F1A102} = {06382AED-685A-4336-B553-DDA7C3A8C616} + {94FD5CF4-A049-45FD-ADBC-15DDBE88A796} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} + {1423494B-2F5D-481D-AA50-1F2D965394DE} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} + {9DB66097-4D62-4E8F-8531-3F44FB8B91D2} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} + {26C5CAF2-FDFD-48C4-97C8-1214AC963D8D} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} + {AF63F2C5-34DC-4E7B-8B79-C6F3D7A0482D} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} + {E8F30DCA-D2B4-41DC-8AB0-54A70EFC90DE} = {9CFDC530-AE9D-4259-BB7D-4DC862F51C2E} + {C8DEE532-AAAA-40FC-962E-F21DAA6C8C6F} = {5D2E938C-2618-4DD9-A439-F193655266A0} + {F001E030-28DE-4C40-B424-C9B50100FEC7} = {5D2E938C-2618-4DD9-A439-F193655266A0} + {35FD5694-B1B8-4FD5-8FA8-896243F99EAB} = {5D2E938C-2618-4DD9-A439-F193655266A0} + {95F18BB5-F085-4CE2-86DC-2322CFF768A2} = {5D2E938C-2618-4DD9-A439-F193655266A0} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B95AEA45-E93F-42C8-990A-4C410797B0C6} diff --git a/cSharp-source/Solution/StackSection/DayQuestions.cs b/cSharp-source/Solution/StackSection/DayQuestions.cs deleted file mode 100644 index ee4b3b1..0000000 --- a/cSharp-source/Solution/StackSection/DayQuestions.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace StackSection; - -public class DayQuestions -{ - #region day 7.13 - - // 735. Asteroid Collision - /* - We are given an array asteroids of integers representing asteroids in a row. - For each asteroid, the absolute value represents its size, - and the sign represents its direction (positive meaning right, negative meaning left). - Each asteroid moves at the same speed. - Find out the state of the asteroids after all collisions. - If two asteroids meet, the smaller one will explode. - If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. - */ - public int[] AsteroidCollision(int[] asteroids) - { - var stack = new Stack(); - - foreach (var num in asteroids) - { - if (num < 0) stack.Push(num); - else - { - // 被撞 不进栈 - if (stack.Count > 0 && stack.Peek() > Math.Abs(num)) continue; - else if (stack.Count > 0 && stack.Peek() > 0 && stack.Peek() == Math.Abs(num)) stack.Pop(); - - while (stack.Count > 0 && stack.Peek() > 0 && stack.Peek() < Math.Abs(num)) stack.Pop(); - } - } - - var res = new int[stack.Count]; - for (int i = stack.Count - 1; i > 0; i--) - { - res[i] = stack.Pop(); - } - return res; - } - - #endregion -} \ No newline at end of file diff --git a/cSharp-source/Solution/StackSection/Program.cs b/cSharp-source/Solution/StackSection/Program.cs deleted file mode 100644 index be38953..0000000 --- a/cSharp-source/Solution/StackSection/Program.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace StackSection; - -internal class Program -{ - static void Main(string[] args) - { - Console.WriteLine("Hello, World!"); - } -} diff --git a/cSharp-source/Solution/StackSection/StackSection.csproj b/cSharp-source/Solution/StackSection/StackSection.csproj deleted file mode 100644 index 74abf5c..0000000 --- a/cSharp-source/Solution/StackSection/StackSection.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - - Exe - net6.0 - enable - enable - - - diff --git a/cSharp-source/Solution/TreeSection/DayQuestion.cs b/cSharp-source/Solution/TreeSection/DayQuestion.cs deleted file mode 100644 index cc475a0..0000000 --- a/cSharp-source/Solution/TreeSection/DayQuestion.cs +++ /dev/null @@ -1,82 +0,0 @@ -namespace TreeSection; -public class DayQuestion -{ - #region day 6.24 - - //515. Find Largest Value in Each Tree Row - // Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed) - - //Input: root = [1,3,2,5,3,null,9] - //Output: [1,3,9] - - //Input: root = [1,2,3] - //Output: [1,3] - - public IList LargestValuesBFS(TreeNode root) - { - IList res = new List(); - if (root == null) return res; - - var treeQueue = new Queue(); - treeQueue.Enqueue(root); - while (treeQueue.Any()) - { - int size = treeQueue.Count, max = treeQueue.Peek().val; - while (size-- > 0) - { - var node = treeQueue.Dequeue(); - max = Math.Max(max, node.val); - if (node.left != null) treeQueue.Enqueue(node.left); - if (node.right != null) treeQueue.Enqueue(node.right); - } - res.Add(max); - } - return res; - } - - int _max = 0; - Dictionary dic = new Dictionary(); - public IList LargestValuesDFS(TreeNode root) - { - IList res = new List(); - DFS(root, 1); - for (int i = 1; i <= _max; i++) res.Add(dic[i]); - return res; - } - - private void DFS(TreeNode root, int depth) - { - if (root == null) return; - _max = Math.Max(_max, depth); - - if (dic.ContainsKey(depth)) - dic[depth] = Math.Max(dic[depth], root.val); - else - dic.Add(depth, root.val); - - DFS(root.left, depth + 1); - DFS(root.right, depth + 1); - } - - #endregion - - #region day 7.21 - - //814. Binary Tree Pruning - public TreeNode PruneTree(TreeNode root) - { - if (root == null) return null; - root.left = PruneTree(root.left); - root.right = PruneTree(root.right); - if (root.left == null && root.right == null && root.val == 0) root = null; - return root; - } - - #endregion - - #region day 7.25 - - // 919. Complete Binary Tree Inserter - - #endregion -} diff --git a/cSharp-source/Solution/TreeSection/FindTreeNode.cs b/cSharp-source/Solution/TreeSection/FindTreeNode.cs deleted file mode 100644 index 62bf674..0000000 --- a/cSharp-source/Solution/TreeSection/FindTreeNode.cs +++ /dev/null @@ -1,57 +0,0 @@ -// ReSharper disable All -namespace TreeSection; - -// Given the root of a binary tree, return the leftmost value in the last row of the tree. -public class FindTreeNode -{ - // DFS use - private int _maxHeight = 0; - private int _ans = 0; - - public int FindBottomLeftValue(TreeNode root) - { - #region BFS - - // var que = new Queue(); - // que.Enqueue(root); - // var ans = root.val; - // while (que.Count > 0) - // { - // var count = que.Count; //获取当前层节点的数量 - // for (int i = 0; i < count; i++) - // { - // var node = que.Dequeue(); - // if (node.left != null) - // que.Enqueue(node.left); - // if (node.right != null) - // que.Enqueue(node.right); - // if (i == 0) ans = node.val; - // } - // } - // return ans; - - #endregion - - #region DFS - - TreeDFS(root, 0); - return _ans; - - #endregion - } - - private void TreeDFS(TreeNode root, int curHeight) - { - if (root == null) return; - - curHeight++; - TreeDFS(root.left, curHeight); - TreeDFS(root.right, curHeight); - // 记录最深层数 (当到达最底层时记录节点值) - if (curHeight > _maxHeight) - { - _maxHeight = curHeight; - _ans = root.val; - } - } -} \ No newline at end of file diff --git a/cSharp-source/Solution/TreeSection/Program.cs b/cSharp-source/Solution/TreeSection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/TreeSection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/TreeSection/TreeNode.cs b/cSharp-source/Solution/TreeSection/TreeNode.cs deleted file mode 100644 index 4f853bf..0000000 --- a/cSharp-source/Solution/TreeSection/TreeNode.cs +++ /dev/null @@ -1,16 +0,0 @@ -// ReSharper disable All -#pragma warning disable CS8625 -namespace TreeSection; - -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; - } -} diff --git a/cSharp-source/Solution/TreeSection/TreeSection.csproj b/cSharp-source/Solution/TreeSection/TreeSection.csproj deleted file mode 100644 index a91a69e..0000000 --- a/cSharp-source/Solution/TreeSection/TreeSection.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - Exe - net6.0 - enable - enable - - - - 1701;1702;8600 - - - - 1701;1702;8600 - - - diff --git a/cSharp-source/Solution/TrieSection/DayQuestion.cs b/cSharp-source/Solution/TrieSection/DayQuestion.cs deleted file mode 100644 index f6eea35..0000000 --- a/cSharp-source/Solution/TrieSection/DayQuestion.cs +++ /dev/null @@ -1,44 +0,0 @@ -namespace TrieSection; - -public class DayQuestion -{ -} - -// 745. Prefix and Suffix Search -public class WordFilter -{ - private string[] words; - - public WordFilter(string[] words) - { - this.words = words; - } - - public int F(string pref, string suff) - { - int n = pref.Length, m = suff.Length; - for (int k = words.Length - 1; k >= 0; k--) - { - var cur = words[k]; - var len = cur.Length; - if (len < n || len < m) continue; - - var ok = true; - for (int i = 0; i < n && ok; i++) - { - if (cur[i] != pref[i]) - ok = false; - } - - for (int i = 0; i < m && ok; i++) - { - if (cur[len - 1 - i] != suff[m - 1 - i]) - ok = false; - } - - if (ok) return k; - } - - return -1; - } -} \ No newline at end of file diff --git a/cSharp-source/Solution/TrieSection/Program.cs b/cSharp-source/Solution/TrieSection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/TrieSection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/TrieSection/TrieSection.csproj b/cSharp-source/Solution/TrieSection/TrieSection.csproj deleted file mode 100644 index b9de063..0000000 --- a/cSharp-source/Solution/TrieSection/TrieSection.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - - Exe - net6.0 - enable - enable - - - -- Gitee From c972e21e7ac4070bebb3ddc8760d865b6633bc34 Mon Sep 17 00:00:00 2001 From: zhousl Date: Wed, 27 Jul 2022 18:39:00 +0800 Subject: [PATCH 11/31] [#update] --- .../0-Test/AlgorithmTest/AlgorithmTest.csproj | 39 ++ .../0-Test/AlgorithmTest/ArrayTest.cs | 39 ++ .../Solution/0-Test/AlgorithmTest/Usings.cs | 2 + .../1-Basic/ArraySection/ArraySection.csproj | 10 + .../1-Basic/ArraySection/DayQuestion.cs | 342 ++++++++++++++++++ .../1-Basic/ArraySection/GlobalUsings.cs | 2 + .../Solution/1-Basic/ArraySection/Matrix.cs | 144 ++++++++ .../Solution/1-Basic/ArraySection/Program.cs | 1 + .../1-Basic/LinkSection/LinkRemove.cs | 20 + .../1-Basic/LinkSection/LinkSection.csproj | 10 + .../Solution/1-Basic/LinkSection/ListNode.cs | 15 + .../Solution/1-Basic/LinkSection/Program.cs | 1 + .../1-Basic/QueueSection/DayQuestion.cs | 30 ++ .../Solution/1-Basic/QueueSection/Program.cs | 1 + .../1-Basic/QueueSection/QueueSection.csproj | 10 + .../1-Basic/StackSection/DayQuestions.cs | 49 +++ .../Solution/1-Basic/StackSection/Program.cs | 9 + .../1-Basic/StackSection/StackSection.csproj | 10 + .../1-Basic/StringSection/DayQuestion.cs | 67 ++++ .../Solution/1-Basic/StringSection/Program.cs | 1 + .../StringSection/StringSection.csproj | 10 + .../1-Basic/TreeSection/CBTInserter.cs | 49 +++ .../1-Basic/TreeSection/DayQuestion.cs | 82 +++++ .../1-Basic/TreeSection/FindTreeNode.cs | 57 +++ .../Solution/1-Basic/TreeSection/Program.cs | 1 + .../Solution/1-Basic/TreeSection/TreeNode.cs | 16 + .../1-Basic/TreeSection/TreeSection.csproj | 18 + .../2-External/DPSection/DPSection.csproj | 10 + .../2-External/DPSection/DayQuestion.cs | 98 +++++ .../Solution/2-External/DPSection/Program.cs | 1 + .../2-External/EncodeSection/DayQuestion.cs | 49 +++ .../EncodeSection/EncodeSection.csproj | 10 + .../OrderSetSection/MyClendarTwo.cs | 39 ++ .../OrderSetSection/OrderSetSection.csproj | 10 + .../2-External/OrderSetSection/Program.cs | 1 + .../2-External/OrderSetSection/SkipList.cs | 67 ++++ .../2-External/TrieSection/DayQuestion.cs | 44 +++ .../2-External/TrieSection/Program.cs | 1 + .../2-External/TrieSection/TrieSection.csproj | 10 + 39 files changed, 1375 insertions(+) create mode 100644 cSharp-source/Solution/0-Test/AlgorithmTest/AlgorithmTest.csproj create mode 100644 cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs create mode 100644 cSharp-source/Solution/0-Test/AlgorithmTest/Usings.cs create mode 100644 cSharp-source/Solution/1-Basic/ArraySection/ArraySection.csproj create mode 100644 cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs create mode 100644 cSharp-source/Solution/1-Basic/ArraySection/GlobalUsings.cs create mode 100644 cSharp-source/Solution/1-Basic/ArraySection/Matrix.cs create mode 100644 cSharp-source/Solution/1-Basic/ArraySection/Program.cs create mode 100644 cSharp-source/Solution/1-Basic/LinkSection/LinkRemove.cs create mode 100644 cSharp-source/Solution/1-Basic/LinkSection/LinkSection.csproj create mode 100644 cSharp-source/Solution/1-Basic/LinkSection/ListNode.cs create mode 100644 cSharp-source/Solution/1-Basic/LinkSection/Program.cs create mode 100644 cSharp-source/Solution/1-Basic/QueueSection/DayQuestion.cs create mode 100644 cSharp-source/Solution/1-Basic/QueueSection/Program.cs create mode 100644 cSharp-source/Solution/1-Basic/QueueSection/QueueSection.csproj create mode 100644 cSharp-source/Solution/1-Basic/StackSection/DayQuestions.cs create mode 100644 cSharp-source/Solution/1-Basic/StackSection/Program.cs create mode 100644 cSharp-source/Solution/1-Basic/StackSection/StackSection.csproj create mode 100644 cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs create mode 100644 cSharp-source/Solution/1-Basic/StringSection/Program.cs create mode 100644 cSharp-source/Solution/1-Basic/StringSection/StringSection.csproj create mode 100644 cSharp-source/Solution/1-Basic/TreeSection/CBTInserter.cs create mode 100644 cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs create mode 100644 cSharp-source/Solution/1-Basic/TreeSection/FindTreeNode.cs create mode 100644 cSharp-source/Solution/1-Basic/TreeSection/Program.cs create mode 100644 cSharp-source/Solution/1-Basic/TreeSection/TreeNode.cs create mode 100644 cSharp-source/Solution/1-Basic/TreeSection/TreeSection.csproj create mode 100644 cSharp-source/Solution/2-External/DPSection/DPSection.csproj create mode 100644 cSharp-source/Solution/2-External/DPSection/DayQuestion.cs create mode 100644 cSharp-source/Solution/2-External/DPSection/Program.cs create mode 100644 cSharp-source/Solution/2-External/EncodeSection/DayQuestion.cs create mode 100644 cSharp-source/Solution/2-External/EncodeSection/EncodeSection.csproj create mode 100644 cSharp-source/Solution/2-External/OrderSetSection/MyClendarTwo.cs create mode 100644 cSharp-source/Solution/2-External/OrderSetSection/OrderSetSection.csproj create mode 100644 cSharp-source/Solution/2-External/OrderSetSection/Program.cs create mode 100644 cSharp-source/Solution/2-External/OrderSetSection/SkipList.cs create mode 100644 cSharp-source/Solution/2-External/TrieSection/DayQuestion.cs create mode 100644 cSharp-source/Solution/2-External/TrieSection/Program.cs create mode 100644 cSharp-source/Solution/2-External/TrieSection/TrieSection.csproj diff --git a/cSharp-source/Solution/0-Test/AlgorithmTest/AlgorithmTest.csproj b/cSharp-source/Solution/0-Test/AlgorithmTest/AlgorithmTest.csproj new file mode 100644 index 0000000..36e7d7a --- /dev/null +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/AlgorithmTest.csproj @@ -0,0 +1,39 @@ + + + + net6.0 + enable + enable + + false + + TestSolution + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + + + + + + + diff --git a/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs b/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs new file mode 100644 index 0000000..7010f6a --- /dev/null +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs @@ -0,0 +1,39 @@ +using Xunit.Abstractions; + +namespace AlgorithmTest; + +public class ArrayTest +{ + private readonly ITestOutputHelper _outputHelper; + + public ArrayTest(ITestOutputHelper outputHelper) + { + _outputHelper = outputHelper; + } + + [Fact] + public void Test() + { + var ans = _Gcd(12, 25); + _outputHelper.WriteLine(ans.ToString()); + } + + [Fact] + public void Test_Parse() + { + var ans = _Parse("+13/24"); + _outputHelper.WriteLine(ans[0].ToString()); + _outputHelper.WriteLine(ans[1].ToString()); + } + + private long _Gcd(long a, long b) => b == 0 ? a : _Gcd(b, a % b); + + private long[] _Parse(string s) + { + int idx = 1; // 去除符号 + while (idx < s.Length && s[idx] != '/') idx++; + var a = Convert.ToInt64(s.Substring(1, idx - 1)); + var b = Convert.ToInt64(s.Substring(idx + 1, s.Length - (idx + 1))); + return new[] { a, b }; + } +} \ No newline at end of file diff --git a/cSharp-source/Solution/0-Test/AlgorithmTest/Usings.cs b/cSharp-source/Solution/0-Test/AlgorithmTest/Usings.cs new file mode 100644 index 0000000..8e27833 --- /dev/null +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/Usings.cs @@ -0,0 +1,2 @@ +global using Xunit; +global using ArraySection; \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/ArraySection/ArraySection.csproj b/cSharp-source/Solution/1-Basic/ArraySection/ArraySection.csproj new file mode 100644 index 0000000..b9de063 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/ArraySection/ArraySection.csproj @@ -0,0 +1,10 @@ + + + + Exe + net6.0 + enable + enable + + + diff --git a/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs new file mode 100644 index 0000000..2e41a15 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs @@ -0,0 +1,342 @@ +namespace ArraySection; + +public class DayQuestion +{ + #region day 6.16 + + // Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. + // + // A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: + // 0 <= i, j < nums.length + // i != j + // nums[i] - nums[j] == k + // Notice that |val| denotes the absolute value of val. + + // Example 1: + // Input: nums = [3,1,4,1,5], k = 2 + // Output: 2 + // Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). + // Although we have two 1s in the input, we should only return the number of unique pairs. + + // Example 2: + // Input: nums = [1,2,3,4,5], k = 1 + // Output: 4 + // Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). + + // Example 3: + // Input: nums = [1,3,1,5,4], k = 0 + // Output: 1 + // Explanation: There is one 0-diff pair in the array, (1, 1). + + public int FindPairs(int[] nums, int k) + { + if (k < 0) return 0; + var dic = new Dictionary(nums.Length); + foreach (var num in nums) + { + if (!dic.ContainsKey(num)) + dic[num] = 0; + dic[num]++; + } + + // 返回数量大于1的 + return k == 0 ? dic.Count(x => x.Value > 1) : dic.Count(item => dic.ContainsKey(item.Key + k)); + } + + #endregion + + #region day 6.17 + + // Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right. + // Note that elements beyond the length of the original array are not written. + // Do the above modifications to the input array in place and do not return anything. + + // Example 1: + // + // Input: arr = [1,0,2,3,0,4,5,0] + // Output: [1,0,0,2,3,0,0,4] + // Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4] + + public void DuplicateZeros(int[] arr) + { + var ans = new List(); + var cursor = 0; + + while (ans.Count < arr.Length) + { + if (arr[cursor] == 0) ans.Add(arr[cursor]); + ans.Add(arr[cursor]); + cursor++; + } + + if (ans.Count > arr.Length) ans.RemoveAt(ans.Count - 1); + + ans.CopyTo(arr, 0); + } + + public void DuplicateZerosV2(int[] arr) + { + var start = 0; + var end = arr.Length; + var index = -1; + + while (start < end) + { + index++; + if (arr[index] != 0) start++; + else start += 2; + } + + var point = end - 1; + if (start == end + 1) + { + arr[point] = 0; + index--; + point--; + } + + while (point >= 0) + { + arr[point--] = arr[index]; + if (arr[index] == 0) + arr[point--] = 0; + index--; + } + } + + #endregion + + #region day 6.21 + + // Given a valid (IPv4) IP address, return a defanged version of that IP address. + // Example 1: + // Input: address = "1.1.1.1" + // Output: "1[.]1[.]1[.]1" + public string DefangIPaddr(string address) + { + var chars = address.ToCharArray(); + var sb = new StringBuilder(); + foreach (var t in chars) + { + if (t == '.') sb.Append('['); + sb.Append(t); + if (t == '.') sb.Append(']'); + } + return sb.ToString(); + } + + #endregion + + #region day 6.23 + + // 30. Substring with Concatenation of All Words + // You are given a string s and an array of strings words of the same length. + // Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, + // in any order, and without any intervening characters. + // You can return the answer in any order. + + //Input: s = "barfoothefoobarman", words = ["foo","bar"] + //Output: [0,9] + //Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively. + //The output order does not matter, returning[9, 0] is fine too. + + public IList FindSubstring(string s, string[] words) + { + IList res = new List(); + int m = words.Length, n = words[0].Length, ls = s.Length; + for (int i = 0; i < n; i++) + { + if (i + m * n > ls) + { + break; + } + Dictionary differ = new Dictionary(); + for (int j = 0; j < m; j++) + { + string word = s.Substring(i + j * n, n); + if (!differ.ContainsKey(word)) + { + differ.Add(word, 0); + } + differ[word]++; + } + foreach (string word in words) + { + if (!differ.ContainsKey(word)) + { + differ.Add(word, 0); + } + differ[word]--; + if (differ[word] == 0) + { + differ.Remove(word); + } + } + for (int start = i; start < ls - m * n + 1; start += n) + { + if (start != i) + { + string word = s.Substring(start + (m - 1) * n, n); + if (!differ.ContainsKey(word)) + { + differ.Add(word, 0); + } + differ[word]++; + if (differ[word] == 0) + { + differ.Remove(word); + } + word = s.Substring(start - n, n); + if (!differ.ContainsKey(word)) + { + differ.Add(word, 0); + } + differ[word]--; + if (differ[word] == 0) + { + differ.Remove(word); + } + } + if (differ.Count == 0) + { + res.Add(start); + } + } + } + return res; + } + + #endregion + + #region day 6.28 + + // 324. Wiggle Sort II + //Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3] > nums[4]... + //You may assume the input array always has a valid answer. + + //Example 1: + //Input: nums = [1,5,1,1,6,4] + //Output: [1,6,1,5,1,4] + //Explanation: [1,4,1,5,1,6] is also accepted. + + //Example 2: + //Input: nums = [1, 3, 2, 2, 3, 1] + //Output: [2,3,1,3,1,2] + + public void WiggleSort(int[] nums) + { + Array.Sort(nums); + var st1 = new Stack(); + var st2 = new Stack(); + int half = (nums.Length - 1) / 2, idx = 0; + while (idx <= half) + { + st1.Push(nums[idx++]); + } + while (idx < nums.Length) + { + st2.Push(nums[idx++]); + } + bool flag = true; + idx = 0; + while (st1.Count > 0 || st2.Count > 0) + { + nums[idx++] = flag ? st1.Pop() : st2.Pop(); + flag = !flag; + } + } + + #endregion + + #region day 7.8 + + public int MinCostToMoveChips(int[] position) + { + int len = position.Length, ans = int.MaxValue; + for (int i = 0; i < len; i++) + { + int a = position[i], cur = 0; + for (int j = 0; j < len; j++) + { + int b = position[j]; + cur += Math.Abs(a - b) % 2; + } + ans = Math.Min(ans, cur); + } + return ans; + } + + #endregion + + #region day 7.18 + + // 565. Array Nesting + public int ArrayNesting(int[] nums) + { + int res = 1; + bool[] visited = new bool[nums.Length]; + + for (int i = 0; i < nums.Length; i++) + { + // 乱序超过一半,则全为乱序了 + if (res > nums.Length / 2) + return res; + // 若该访问点被某序列访问过,那么以这个元素为头的序列肯定不为最长 + if (visited[nums[i]] == true) + continue; + + int len = 1; + int next = nums[nums[i]]; + while (next != nums[i]) + { + visited[next] = true; + + len++; + next = nums[next]; + } + res = len > res ? len : res; + } + return res; + } + + #endregion + + #region day 7.22 + + //757. Set Intersection Size At Least Two + //An integer interval[a, b] (for integers a o1[0] == o2[0] ? o2[1].CompareTo(o1[1]) : o1[0].CompareTo(o2[0])); + var n = intervals.Length; + + var cur = intervals[n - 1][0]; + var next = intervals[n - 1][0] + 1; + var ans = 2; + + for (int i = n - 2; i >= 0; i--) + { + if (intervals[i][1] >= next) continue; + else if (intervals[i][1] < cur) + { + cur = intervals[i][0]; + next = intervals[i][0] + 1; + ans += 2; + } + else + { + next = cur; + cur = intervals[i][0]; + ans++; + } + } + return ans; + } + + #endregion +} \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/ArraySection/GlobalUsings.cs b/cSharp-source/Solution/1-Basic/ArraySection/GlobalUsings.cs new file mode 100644 index 0000000..ad56d1b --- /dev/null +++ b/cSharp-source/Solution/1-Basic/ArraySection/GlobalUsings.cs @@ -0,0 +1,2 @@ +global using System.Text; +global using System.Diagnostics.CodeAnalysis; diff --git a/cSharp-source/Solution/1-Basic/ArraySection/Matrix.cs b/cSharp-source/Solution/1-Basic/ArraySection/Matrix.cs new file mode 100644 index 0000000..d975ea6 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/ArraySection/Matrix.cs @@ -0,0 +1,144 @@ +namespace ArraySection; + +public class Matrix +{ + #region 59 + + // 59. Spiral Matrix II + // Given a positive integer n, generate an n x n matrix filled with elements + // from 1 to n2 in spiral order. + + // Input: n = 3 + // Output: [[1,2,3],[8,9,4],[7,6,5]] + // + // Input: n = 1 + // Output: [[1]] + + public int[][] GenerateMatrix(int n) + { + // Init array + var matrix = new int[n][]; + for (var i = 0; i < n; i++) + { + matrix[i] = new int[n]; + } + + var left = 0; + var right = n - 1; + var top = 0; + var bottom = n - 1; + var start = 1; + var end = n * n; + + // start rotate + while (start <= end) + { + for (int i = left; i <= right; i++) + { + matrix[top][i] = start; + start++; + } + + top++; + + for (int i = top; i <= bottom; i++) + { + matrix[i][right] = start; + start++; + } + + right--; + + for (int i = right; i >= left; i--) + { + matrix[bottom][i] = start; + start++; + } + + bottom--; + + for (int i = bottom; i >= top; i--) + { + matrix[i][left] = start; + start++; + } + + left++; + } + + return matrix; + } + + #endregion + + #region 1257 + + // 1252. Cells with Odd Values in a Matrix + + // There is an m x n matrix that is initialized to all 0's. + // There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix. + // For each location indices[i], do both of the following: + + // Increment all the cells on row ri. + // Increment all the cells on column ci. + // Given m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices. + + [SuppressMessage("ReSharper", "AssignmentInConditionalExpression")] + public int OddCells(int m, int n, int[][] indices) + { + var row = new int[m]; + var col = new int[n]; + + foreach (var index in indices) + { + row[index[0]]++; + col[index[1]]++; + } + + int oddRow = row.Count(r => (r & 1) == 0); + int oddCol = col.Count(c => (c & 1) == 0); + + return (oddRow * n) + (oddCol * m) - 2 * (oddCol * oddRow); + } + + #endregion + + #region 1260 + + //Given a 2D grid of size m x n and an integer k.You need to shift the grid k times. + + //In one shift operation: + //Element at grid[i][j] moves to grid[i][j + 1]. + //Element at grid[i][n - 1] moves to grid[i + 1][0]. + //Element at grid[m - 1][n - 1] moves to grid[0][0]. + //Return the 2D grid after applying shift operation k times. + + public IList> ShiftGrid(int[][] grid, int k) + { + int[] nums = new int[grid[0].Length * grid.Length]; + + foreach (var row in grid) + { + foreach (var num in row) + { + k %= nums.Length; + nums[k++] = num; + } + } + + IList> result = new List>(nums.Length); + k = 0; + for (int i = 0; i < grid.Length; i++) + { + var tempList = new List(grid[0].Length); + for (int j = 0; j < grid[0].Length; j++) + { + tempList.Add(nums[k++]); + } + result.Add(tempList); + } + return result; + } + + #endregion +} \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/ArraySection/Program.cs b/cSharp-source/Solution/1-Basic/ArraySection/Program.cs new file mode 100644 index 0000000..837131c --- /dev/null +++ b/cSharp-source/Solution/1-Basic/ArraySection/Program.cs @@ -0,0 +1 @@ +Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/LinkSection/LinkRemove.cs b/cSharp-source/Solution/1-Basic/LinkSection/LinkRemove.cs new file mode 100644 index 0000000..4d534a5 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/LinkSection/LinkRemove.cs @@ -0,0 +1,20 @@ +namespace LinkSection; + +public class LinkRemove +{ + public ListNode RemoveElements(ListNode head, int val) + { + var dummyLink = new ListNode(); + dummyLink.next = head; + var cur = dummyLink; + + while (cur?.next != null) + { + if (cur.next.val == val) + cur.next = cur.next.next; + else + cur = cur.next; + } + return dummyLink.next; + } +} \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/LinkSection/LinkSection.csproj b/cSharp-source/Solution/1-Basic/LinkSection/LinkSection.csproj new file mode 100644 index 0000000..b9de063 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/LinkSection/LinkSection.csproj @@ -0,0 +1,10 @@ + + + + Exe + net6.0 + enable + enable + + + diff --git a/cSharp-source/Solution/1-Basic/LinkSection/ListNode.cs b/cSharp-source/Solution/1-Basic/LinkSection/ListNode.cs new file mode 100644 index 0000000..a428592 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/LinkSection/ListNode.cs @@ -0,0 +1,15 @@ +// ReSharper disable All +#pragma warning disable CS8625 + +namespace LinkSection; + +public class ListNode +{ + public int val; + public ListNode next; + public ListNode(int val = 0, ListNode next = null) + { + this.val = val; + this.next = next; + } +} diff --git a/cSharp-source/Solution/1-Basic/LinkSection/Program.cs b/cSharp-source/Solution/1-Basic/LinkSection/Program.cs new file mode 100644 index 0000000..837131c --- /dev/null +++ b/cSharp-source/Solution/1-Basic/LinkSection/Program.cs @@ -0,0 +1 @@ +Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/QueueSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/QueueSection/DayQuestion.cs new file mode 100644 index 0000000..34c0c03 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/QueueSection/DayQuestion.cs @@ -0,0 +1,30 @@ +namespace QueueSection; + +public class DayQuestion +{ +} + +// 剑指 Offer II 041. 滑动窗口的平均值 +public class MovingAverage +{ + private int[] arr; + private int _size, sum, rear, front; + + /** Initialize your data structure here. */ + public MovingAverage(int size) + { + this.arr = new int [10010]; + this._size = size; + } + + public double Next(int val) + { + sum += arr[rear++] = val; + if (rear - front > _size) + { + sum -= arr[front]; + front++; + } + return (double)sum / (rear - front); + } +} \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/QueueSection/Program.cs b/cSharp-source/Solution/1-Basic/QueueSection/Program.cs new file mode 100644 index 0000000..837131c --- /dev/null +++ b/cSharp-source/Solution/1-Basic/QueueSection/Program.cs @@ -0,0 +1 @@ +Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/QueueSection/QueueSection.csproj b/cSharp-source/Solution/1-Basic/QueueSection/QueueSection.csproj new file mode 100644 index 0000000..b9de063 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/QueueSection/QueueSection.csproj @@ -0,0 +1,10 @@ + + + + Exe + net6.0 + enable + enable + + + diff --git a/cSharp-source/Solution/1-Basic/StackSection/DayQuestions.cs b/cSharp-source/Solution/1-Basic/StackSection/DayQuestions.cs new file mode 100644 index 0000000..ee4b3b1 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/StackSection/DayQuestions.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StackSection; + +public class DayQuestions +{ + #region day 7.13 + + // 735. Asteroid Collision + /* + We are given an array asteroids of integers representing asteroids in a row. + For each asteroid, the absolute value represents its size, + and the sign represents its direction (positive meaning right, negative meaning left). + Each asteroid moves at the same speed. + Find out the state of the asteroids after all collisions. + If two asteroids meet, the smaller one will explode. + If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. + */ + public int[] AsteroidCollision(int[] asteroids) + { + var stack = new Stack(); + + foreach (var num in asteroids) + { + if (num < 0) stack.Push(num); + else + { + // 被撞 不进栈 + if (stack.Count > 0 && stack.Peek() > Math.Abs(num)) continue; + else if (stack.Count > 0 && stack.Peek() > 0 && stack.Peek() == Math.Abs(num)) stack.Pop(); + + while (stack.Count > 0 && stack.Peek() > 0 && stack.Peek() < Math.Abs(num)) stack.Pop(); + } + } + + var res = new int[stack.Count]; + for (int i = stack.Count - 1; i > 0; i--) + { + res[i] = stack.Pop(); + } + return res; + } + + #endregion +} \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/StackSection/Program.cs b/cSharp-source/Solution/1-Basic/StackSection/Program.cs new file mode 100644 index 0000000..be38953 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/StackSection/Program.cs @@ -0,0 +1,9 @@ +namespace StackSection; + +internal class Program +{ + static void Main(string[] args) + { + Console.WriteLine("Hello, World!"); + } +} diff --git a/cSharp-source/Solution/1-Basic/StackSection/StackSection.csproj b/cSharp-source/Solution/1-Basic/StackSection/StackSection.csproj new file mode 100644 index 0000000..74abf5c --- /dev/null +++ b/cSharp-source/Solution/1-Basic/StackSection/StackSection.csproj @@ -0,0 +1,10 @@ + + + + Exe + net6.0 + enable + enable + + + diff --git a/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs new file mode 100644 index 0000000..f19808f --- /dev/null +++ b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs @@ -0,0 +1,67 @@ +namespace StringSection; + +public class DayQuestion +{ + #region day 7.27 + + // 592. Fraction Addition and Subtraction + public string FractionAddition(string expression) + { + int len = expression.Length; + string ans = String.Empty; + char[] cs = expression.ToCharArray(); + + for (int i = 0; i < len;) + { + int j = i + 1; + while (j < len && cs[j] != '+' && cs[j] != '-') j++; + var num = expression.Substring(i, j - i); + if (cs[i] != '+' && cs[i] != '-') num = "+" + num; + if (!ans.Equals("")) ans = _Calculate(num, ans); + else ans = num; + i = j; + } + + return ans[0] == '+' ? ans.Substring(1, ans.Length - 1) : ans; + } + + private string _Calculate(string a, string b) + { + bool fa = a[0] == '+', fb = b[0] == '+'; + if (!fa && fb) return _Calculate(b, a); + + long[] p = _Parse(a), q = _Parse(b); + long p1 = p[0] * q[1], q1 = q[0] * p[1]; + if (fa && fb) // ADD + { + long son = p1 + q1, mom = q[1] + p[1], gcd = _Gcd(son, mom); + return $"+{son / gcd}/{mom / gcd}"; + } + else if (!fa && !fb) + { + long son = p1 + q1, mom = q[1] + p[1], gcd = _Gcd(son, mom); + return $"-{son / gcd}/{mom / gcd}"; + } + else // Reduce + { + long son = p1 - q1, mom = q[1] + p[1], gcd = _Gcd(Math.Abs(son), mom); + var ans = (son / gcd) + "/" + (mom / gcd); + if (p1 >= q1) ans = $"+{ans}"; + return ans; + } + } + + private long[] _Parse(string s) + { + int idx = 1; // 去除符号 + while (idx < s.Length && s[idx] != '/') idx++; + var a = Convert.ToInt64(s.Substring(1, idx - 1)); + var b = Convert.ToInt64(s.Substring(idx + 1, s.Length - (idx + 1))); + return new[] { a, b }; + } + + // 最大公约数化简 + private long _Gcd(long a, long b) => b == 0 ? a : _Gcd(b, a % b); + + #endregion +} \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/StringSection/Program.cs b/cSharp-source/Solution/1-Basic/StringSection/Program.cs new file mode 100644 index 0000000..837131c --- /dev/null +++ b/cSharp-source/Solution/1-Basic/StringSection/Program.cs @@ -0,0 +1 @@ +Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/StringSection/StringSection.csproj b/cSharp-source/Solution/1-Basic/StringSection/StringSection.csproj new file mode 100644 index 0000000..b9de063 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/StringSection/StringSection.csproj @@ -0,0 +1,10 @@ + + + + Exe + net6.0 + enable + enable + + + diff --git a/cSharp-source/Solution/1-Basic/TreeSection/CBTInserter.cs b/cSharp-source/Solution/1-Basic/TreeSection/CBTInserter.cs new file mode 100644 index 0000000..5bc7ba7 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/TreeSection/CBTInserter.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TreeSection; +public class CBTInserter +{ + private TreeNode _root; + // 只用于存取可插入的叶子节点 + private Queue _queue = new Queue(); + + public CBTInserter(TreeNode root) + { + _root = root; + Queue tempTrees = new Queue(); + tempTrees.Enqueue(root); + + while (tempTrees.Count > 0) + { + TreeNode cur = tempTrees.Dequeue(); + if (cur.left != null) tempTrees.Enqueue(cur.left); + if (cur.right != null) tempTrees.Enqueue(cur.right); + + if (cur.left == null || cur.right == null) + _queue.Enqueue(cur); + } + } + + public int Insert(int val) + { + TreeNode node = new TreeNode(val); + TreeNode cur = _queue.Peek(); + + if (cur.left == null) cur.left = node; + else if (cur.right == null) + { + cur.right = node; + // 右节点新增后,该节点不是叶子节点了,从可插入队列中移除 + _queue.Dequeue(); + } + // 新增可插入叶子节点 + _queue.Enqueue(node); + return cur.val; + } + + public TreeNode Get_root() => _root; +} diff --git a/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs new file mode 100644 index 0000000..cc475a0 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs @@ -0,0 +1,82 @@ +namespace TreeSection; +public class DayQuestion +{ + #region day 6.24 + + //515. Find Largest Value in Each Tree Row + // Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed) + + //Input: root = [1,3,2,5,3,null,9] + //Output: [1,3,9] + + //Input: root = [1,2,3] + //Output: [1,3] + + public IList LargestValuesBFS(TreeNode root) + { + IList res = new List(); + if (root == null) return res; + + var treeQueue = new Queue(); + treeQueue.Enqueue(root); + while (treeQueue.Any()) + { + int size = treeQueue.Count, max = treeQueue.Peek().val; + while (size-- > 0) + { + var node = treeQueue.Dequeue(); + max = Math.Max(max, node.val); + if (node.left != null) treeQueue.Enqueue(node.left); + if (node.right != null) treeQueue.Enqueue(node.right); + } + res.Add(max); + } + return res; + } + + int _max = 0; + Dictionary dic = new Dictionary(); + public IList LargestValuesDFS(TreeNode root) + { + IList res = new List(); + DFS(root, 1); + for (int i = 1; i <= _max; i++) res.Add(dic[i]); + return res; + } + + private void DFS(TreeNode root, int depth) + { + if (root == null) return; + _max = Math.Max(_max, depth); + + if (dic.ContainsKey(depth)) + dic[depth] = Math.Max(dic[depth], root.val); + else + dic.Add(depth, root.val); + + DFS(root.left, depth + 1); + DFS(root.right, depth + 1); + } + + #endregion + + #region day 7.21 + + //814. Binary Tree Pruning + public TreeNode PruneTree(TreeNode root) + { + if (root == null) return null; + root.left = PruneTree(root.left); + root.right = PruneTree(root.right); + if (root.left == null && root.right == null && root.val == 0) root = null; + return root; + } + + #endregion + + #region day 7.25 + + // 919. Complete Binary Tree Inserter + + #endregion +} diff --git a/cSharp-source/Solution/1-Basic/TreeSection/FindTreeNode.cs b/cSharp-source/Solution/1-Basic/TreeSection/FindTreeNode.cs new file mode 100644 index 0000000..62bf674 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/TreeSection/FindTreeNode.cs @@ -0,0 +1,57 @@ +// ReSharper disable All +namespace TreeSection; + +// Given the root of a binary tree, return the leftmost value in the last row of the tree. +public class FindTreeNode +{ + // DFS use + private int _maxHeight = 0; + private int _ans = 0; + + public int FindBottomLeftValue(TreeNode root) + { + #region BFS + + // var que = new Queue(); + // que.Enqueue(root); + // var ans = root.val; + // while (que.Count > 0) + // { + // var count = que.Count; //获取当前层节点的数量 + // for (int i = 0; i < count; i++) + // { + // var node = que.Dequeue(); + // if (node.left != null) + // que.Enqueue(node.left); + // if (node.right != null) + // que.Enqueue(node.right); + // if (i == 0) ans = node.val; + // } + // } + // return ans; + + #endregion + + #region DFS + + TreeDFS(root, 0); + return _ans; + + #endregion + } + + private void TreeDFS(TreeNode root, int curHeight) + { + if (root == null) return; + + curHeight++; + TreeDFS(root.left, curHeight); + TreeDFS(root.right, curHeight); + // 记录最深层数 (当到达最底层时记录节点值) + if (curHeight > _maxHeight) + { + _maxHeight = curHeight; + _ans = root.val; + } + } +} \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/TreeSection/Program.cs b/cSharp-source/Solution/1-Basic/TreeSection/Program.cs new file mode 100644 index 0000000..837131c --- /dev/null +++ b/cSharp-source/Solution/1-Basic/TreeSection/Program.cs @@ -0,0 +1 @@ +Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/TreeSection/TreeNode.cs b/cSharp-source/Solution/1-Basic/TreeSection/TreeNode.cs new file mode 100644 index 0000000..4f853bf --- /dev/null +++ b/cSharp-source/Solution/1-Basic/TreeSection/TreeNode.cs @@ -0,0 +1,16 @@ +// ReSharper disable All +#pragma warning disable CS8625 +namespace TreeSection; + +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; + } +} diff --git a/cSharp-source/Solution/1-Basic/TreeSection/TreeSection.csproj b/cSharp-source/Solution/1-Basic/TreeSection/TreeSection.csproj new file mode 100644 index 0000000..a91a69e --- /dev/null +++ b/cSharp-source/Solution/1-Basic/TreeSection/TreeSection.csproj @@ -0,0 +1,18 @@ + + + + Exe + net6.0 + enable + enable + + + + 1701;1702;8600 + + + + 1701;1702;8600 + + + diff --git a/cSharp-source/Solution/2-External/DPSection/DPSection.csproj b/cSharp-source/Solution/2-External/DPSection/DPSection.csproj new file mode 100644 index 0000000..74abf5c --- /dev/null +++ b/cSharp-source/Solution/2-External/DPSection/DPSection.csproj @@ -0,0 +1,10 @@ + + + + Exe + net6.0 + enable + enable + + + diff --git a/cSharp-source/Solution/2-External/DPSection/DayQuestion.cs b/cSharp-source/Solution/2-External/DPSection/DayQuestion.cs new file mode 100644 index 0000000..6d11dbd --- /dev/null +++ b/cSharp-source/Solution/2-External/DPSection/DayQuestion.cs @@ -0,0 +1,98 @@ +namespace DPSection; + +public class DayQuestion +{ + #region day 6.25 + + //假如有一排房子,共 n 个,每个房子可以被粉刷成红色、蓝色或者绿色这三种颜色中的一种,你需要粉刷所有的房子并且使其相邻的两个房子颜色不能相同。 + //当然,因为市场上不同颜色油漆的价格不同,所以房子粉刷成不同颜色的花费成本也是不同的。每个房子粉刷成不同颜色的花费是以一个 n x 3 的正整数矩阵 costs 来表示的。 + //例如,costs[0][0] 表示第 0 号房子粉刷成红色的成本花费;costs[1][2] 表示第 1 号房子粉刷成绿色的花费,以此类推。 + //请计算出粉刷完所有房子最少的花费成本。 + + //示例 1: + //输入: costs = [[17,2,17],[16,16,5],[14,3,19]] + //输出: 10 + //解释: 将 0 号房子粉刷成蓝色,1 号房子粉刷成绿色,2 号房子粉刷成蓝色。 最少花费: 2 + 5 + 3 = 10。 + + //示例 2: + //输入: costs = [[7,6,2]] + //输出: 2 + + public int MinCost(int[][] costs) + { + var size = costs.Length; + int a = costs[0][0], b = costs[0][1], c = costs[0][2]; + for (int i = 1; i < size; i++) + { + // 由其他的两种不同颜色决定 + int d = Math.Min(b, c) + costs[i][0]; + int e = Math.Min(a, c) + costs[i][1]; + int f = Math.Min(a, b) + costs[i][2]; + a = d; b = e; c = f; + } + return Math.Min(a, Math.Min(b, c)); + } + + #endregion + + #region day 6.27 + + // Given an array of strings strs, return the length of the longest uncommon subsequence between them. + // If the longest uncommon subsequence does not exist, return -1. + // An uncommon subsequence between an array of strings is a string that is a subsequence of one string + // but not the others. + + // Example 1: + // Input: strs = ["aba","cdc","eae"] + // Output: 3 + + // Example 2: + // Input: strs = ["aaa","aaa","aa"] + // Output: -1 + + public int FindLUSlength(string[] strs) + { + int n = strs.Length; + int res = -1; + + for (int i = 0; i < n; i++) + { + if (strs[i].Length <= res) continue; + bool notSame = true; + for (int j = 0; j < n && notSame; j++) + { + if (i == j) continue; + if (Check(strs[i], strs[j])) notSame = false; + } + if (notSame) res = strs[i].Length; + } + return res; + } + + private bool Check(string s1, string s2) + { + int n = s1.Length, m = s2.Length; + if (m < n) return false; + + int[][] f = new int[n + 1][]; + for (int i = 0; i < n + 1; i++) + f[i] = new int[m + 1]; + + for (int i = 1; i <= n; i++) + { + for (int j = 1; j <= m; j++) + { + if (s1[i - 1] == s2[j - 1]) + f[i][j] = f[i - 1][j - 1] + 1; + else + f[i][j] = f[i - 1][j - 1]; + + f[i][j] = Math.Max(f[i][j], Math.Max(f[i][j - 1], f[i - 1][j])); + if (f[i][j] == n) return true; + } + } + return false; + } + + #endregion +} diff --git a/cSharp-source/Solution/2-External/DPSection/Program.cs b/cSharp-source/Solution/2-External/DPSection/Program.cs new file mode 100644 index 0000000..837131c --- /dev/null +++ b/cSharp-source/Solution/2-External/DPSection/Program.cs @@ -0,0 +1 @@ +Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/2-External/EncodeSection/DayQuestion.cs b/cSharp-source/Solution/2-External/EncodeSection/DayQuestion.cs new file mode 100644 index 0000000..0581947 --- /dev/null +++ b/cSharp-source/Solution/2-External/EncodeSection/DayQuestion.cs @@ -0,0 +1,49 @@ +namespace EncodeSection; + +public class DayQuestion +{ + #region Day 6.29 + + // 535. Encode and Decode TinyURL + // TinyURL is a URL shortening service where you enter a URL such as + // https:leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. + // Design a class to encode a URL and decode a tiny URL. + // There is no restriction on how your encode/decode algorithm should work. + // You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. + + // Base62 + private Dictionary _tiny2Origin = new Dictionary(); + private Dictionary _origin2Tiny = new Dictionary(); + private const string _codeStr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; + private const string _prefix = "https://xieyi.com/tiny/"; + private const int _k = 6; + + public string OriginEncode(string longUrl) + { + var random = new Random(); + while (!_origin2Tiny.ContainsKey(longUrl)) + { + // generate keys + var keys = new char[_k]; + for (var i = 0; i < _k; i++) keys[i] = _codeStr[random.Next(_codeStr.Length)]; + + var redirect = _prefix + keys.ToString(); + if (_tiny2Origin.ContainsKey(redirect)) continue; + + _tiny2Origin.Add(redirect, longUrl); + _origin2Tiny.Add(longUrl, redirect); + } + + return _origin2Tiny[longUrl]; + } + + public string TinyDecode(string shortUrl) => _tiny2Origin[shortUrl]; + + #endregion + + #region Day 7.14 + + + + #endregion +} \ No newline at end of file diff --git a/cSharp-source/Solution/2-External/EncodeSection/EncodeSection.csproj b/cSharp-source/Solution/2-External/EncodeSection/EncodeSection.csproj new file mode 100644 index 0000000..6afd605 --- /dev/null +++ b/cSharp-source/Solution/2-External/EncodeSection/EncodeSection.csproj @@ -0,0 +1,10 @@ + + + + net6.0 + enable + enable + EncodeSolution + + + diff --git a/cSharp-source/Solution/2-External/OrderSetSection/MyClendarTwo.cs b/cSharp-source/Solution/2-External/OrderSetSection/MyClendarTwo.cs new file mode 100644 index 0000000..b29b2e1 --- /dev/null +++ b/cSharp-source/Solution/2-External/OrderSetSection/MyClendarTwo.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrderSetSection; + +public class MyCalendarTwo +{ + private SortedDictionary calendar; + + public MyCalendarTwo() + { + calendar = new SortedDictionary(); + } + + public bool Book(int start, int end) + { + int res = 0, maxBook = 0; + + if (!calendar.TryAdd(start, 1)) calendar[start] += 1; + if (!calendar.TryAdd(end, -1)) calendar[end] -= 1; + + foreach (var item in calendar) + { + maxBook += item.Value; + res = Math.Max(maxBook, res); + if (maxBook > 2) + { + calendar[start] -= 1; + calendar[end] += 1; + return false; + } + } + + return true; + } +} diff --git a/cSharp-source/Solution/2-External/OrderSetSection/OrderSetSection.csproj b/cSharp-source/Solution/2-External/OrderSetSection/OrderSetSection.csproj new file mode 100644 index 0000000..74abf5c --- /dev/null +++ b/cSharp-source/Solution/2-External/OrderSetSection/OrderSetSection.csproj @@ -0,0 +1,10 @@ + + + + Exe + net6.0 + enable + enable + + + diff --git a/cSharp-source/Solution/2-External/OrderSetSection/Program.cs b/cSharp-source/Solution/2-External/OrderSetSection/Program.cs new file mode 100644 index 0000000..837131c --- /dev/null +++ b/cSharp-source/Solution/2-External/OrderSetSection/Program.cs @@ -0,0 +1 @@ +Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/2-External/OrderSetSection/SkipList.cs b/cSharp-source/Solution/2-External/OrderSetSection/SkipList.cs new file mode 100644 index 0000000..041d19e --- /dev/null +++ b/cSharp-source/Solution/2-External/OrderSetSection/SkipList.cs @@ -0,0 +1,67 @@ +namespace OrderSetSection; + +public class SkipList +{ + private const int level = 10; + private Random _random = new Random(); + + class Node + { + public int val { get; set; } + public Node[] ne { get; set; } = new Node[level]; + + public Node(int _val) + { + val = _val; + } + } + + private Node se = new Node(-1); + + + /// + /// 查找出每一层比 target 严格小的最后一个节点,将其存成 ns 数组。 + /// 即 ns[i] 为 level=i 层严格比 target 小的最后一个节点。 + /// + /// + /// + void Find(int target, Node[] ns) + { + Node cur = se; + for (int i = level - 1; i >= 0; i--) + { + while (cur.ne[i] != null && cur.ne[i].val < target) cur = cur.ne[i]; + ns[i] = cur; // 找到大于target的链表层 + } + } + + public bool Search(int t) + { + Node[] ns = new Node[level]; + Find(t, ns); + return ns[0].ne[0] != null && ns[0].ne[0].val == t; + } + + public void Add(int t) + { + Node[] ns = new Node[level]; + Find(t, ns); + Node node = new Node(t); + for (int i = 0; i < level; i++) + { + node.ne[i] = ns[i].ne[i]; + ns[i].ne[i] = node; + if (_random.Next(2) == 0) break; + } + } + + public Boolean Erase(int t) + { + Node[] ns = new Node[level]; + Find(t, ns); + Node node = ns[0].ne[0]; + if (node == null || node.val != t) return false; + for (int i = 0; i < level && ns[i].ne[i] == node; i++) ns[i].ne[i] = ns[i].ne[i].ne[i]; + return true; + } +} \ No newline at end of file diff --git a/cSharp-source/Solution/2-External/TrieSection/DayQuestion.cs b/cSharp-source/Solution/2-External/TrieSection/DayQuestion.cs new file mode 100644 index 0000000..f6eea35 --- /dev/null +++ b/cSharp-source/Solution/2-External/TrieSection/DayQuestion.cs @@ -0,0 +1,44 @@ +namespace TrieSection; + +public class DayQuestion +{ +} + +// 745. Prefix and Suffix Search +public class WordFilter +{ + private string[] words; + + public WordFilter(string[] words) + { + this.words = words; + } + + public int F(string pref, string suff) + { + int n = pref.Length, m = suff.Length; + for (int k = words.Length - 1; k >= 0; k--) + { + var cur = words[k]; + var len = cur.Length; + if (len < n || len < m) continue; + + var ok = true; + for (int i = 0; i < n && ok; i++) + { + if (cur[i] != pref[i]) + ok = false; + } + + for (int i = 0; i < m && ok; i++) + { + if (cur[len - 1 - i] != suff[m - 1 - i]) + ok = false; + } + + if (ok) return k; + } + + return -1; + } +} \ No newline at end of file diff --git a/cSharp-source/Solution/2-External/TrieSection/Program.cs b/cSharp-source/Solution/2-External/TrieSection/Program.cs new file mode 100644 index 0000000..837131c --- /dev/null +++ b/cSharp-source/Solution/2-External/TrieSection/Program.cs @@ -0,0 +1 @@ +Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/2-External/TrieSection/TrieSection.csproj b/cSharp-source/Solution/2-External/TrieSection/TrieSection.csproj new file mode 100644 index 0000000..b9de063 --- /dev/null +++ b/cSharp-source/Solution/2-External/TrieSection/TrieSection.csproj @@ -0,0 +1,10 @@ + + + + Exe + net6.0 + enable + enable + + + -- Gitee From 3da8ebe19fb44a3808ec65fe68798334bbd82073 Mon Sep 17 00:00:00 2001 From: zhousl Date: Fri, 29 Jul 2022 14:41:41 +0800 Subject: [PATCH 12/31] [#update] --- .../0-Test/AlgorithmTest/ArrayTest.cs | 2 -- .../0-Test/AlgorithmTest/StringTest.cs | 21 ++++++++++++++ .../Solution/0-Test/AlgorithmTest/Usings.cs | 4 ++- .../1-Basic/ArraySection/DayQuestion.cs | 27 +++++++++++++++-- .../1-Basic/StringSection/DayQuestion.cs | 8 ++--- .../2-External/MathSection/DayQuestion.cs | 22 ++++++++++++++ .../2-External/MathSection/MathSection.csproj | 10 +++++++ .../2-External/MathSection/Program.cs | 1 + cSharp-source/Solution/Solution.sln | 29 ++++++++++++------- 9 files changed, 104 insertions(+), 20 deletions(-) create mode 100644 cSharp-source/Solution/0-Test/AlgorithmTest/StringTest.cs create mode 100644 cSharp-source/Solution/2-External/MathSection/DayQuestion.cs create mode 100644 cSharp-source/Solution/2-External/MathSection/MathSection.csproj create mode 100644 cSharp-source/Solution/2-External/MathSection/Program.cs diff --git a/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs b/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs index 7010f6a..b114213 100644 --- a/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs @@ -1,5 +1,3 @@ -using Xunit.Abstractions; - namespace AlgorithmTest; public class ArrayTest diff --git a/cSharp-source/Solution/0-Test/AlgorithmTest/StringTest.cs b/cSharp-source/Solution/0-Test/AlgorithmTest/StringTest.cs new file mode 100644 index 0000000..bd411ca --- /dev/null +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/StringTest.cs @@ -0,0 +1,21 @@ +using DayQuestion = StringSection.DayQuestion; + +namespace AlgorithmTest; + +public class StringTest +{ + private readonly ITestOutputHelper _outputHelper; + public StringTest(ITestOutputHelper outputHelper) + { + _outputHelper = outputHelper; + } + + [Fact] + public void Test_FractionAddition() + { + var invoker = new DayQuestion(); + var parameters = "-1/2+1/2+1/3"; + var ans = invoker.FractionAddition(parameters); + _outputHelper.WriteLine(ans.ToString()); + } +} diff --git a/cSharp-source/Solution/0-Test/AlgorithmTest/Usings.cs b/cSharp-source/Solution/0-Test/AlgorithmTest/Usings.cs index 8e27833..fda36ad 100644 --- a/cSharp-source/Solution/0-Test/AlgorithmTest/Usings.cs +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/Usings.cs @@ -1,2 +1,4 @@ global using Xunit; -global using ArraySection; \ No newline at end of file +global using ArraySection; +global using StringSection; +global using Xunit.Abstractions; \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs index 2e41a15..18c72fd 100644 --- a/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs @@ -282,7 +282,7 @@ public class DayQuestion if (res > nums.Length / 2) return res; // 若该访问点被某序列访问过,那么以这个元素为头的序列肯定不为最长 - if (visited[nums[i]] == true) + if (visited[nums[i]]) continue; int len = 1; @@ -322,7 +322,8 @@ public class DayQuestion for (int i = n - 2; i >= 0; i--) { if (intervals[i][1] >= next) continue; - else if (intervals[i][1] < cur) + + if (intervals[i][1] < cur) { cur = intervals[i][0]; next = intervals[i][0] + 1; @@ -339,4 +340,26 @@ public class DayQuestion } #endregion + + #region day 7.28 + + //1331. Rank Transform of an Array + public int[] ArrayRankTransform(int[] arr) + { + var sortArr = new int[arr.Length]; + Array.Copy(arr, sortArr, arr.Length); + Array.Sort(sortArr); + + var rankMap = new Dictionary(); + var index = 1; + for (int i = 0; i < sortArr.Length; i++) + { + if (!rankMap.ContainsKey(sortArr[i])) rankMap.Add(sortArr[i], index++); + } + + for (int i = 0; i < arr.Length; i++) arr[i] = rankMap[arr[i]]; + return arr; + } + + #endregion } \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs index f19808f..7abff6d 100644 --- a/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs @@ -8,7 +8,7 @@ public class DayQuestion public string FractionAddition(string expression) { int len = expression.Length; - string ans = String.Empty; + string ans = string.Empty; char[] cs = expression.ToCharArray(); for (int i = 0; i < len;) @@ -34,17 +34,17 @@ public class DayQuestion long p1 = p[0] * q[1], q1 = q[0] * p[1]; if (fa && fb) // ADD { - long son = p1 + q1, mom = q[1] + p[1], gcd = _Gcd(son, mom); + long son = p1 + q1, mom = q[1] * p[1], gcd = _Gcd(son, mom); return $"+{son / gcd}/{mom / gcd}"; } else if (!fa && !fb) { - long son = p1 + q1, mom = q[1] + p[1], gcd = _Gcd(son, mom); + long son = p1 + q1, mom = q[1] * p[1], gcd = _Gcd(son, mom); return $"-{son / gcd}/{mom / gcd}"; } else // Reduce { - long son = p1 - q1, mom = q[1] + p[1], gcd = _Gcd(Math.Abs(son), mom); + long son = p1 - q1, mom = q[1] * p[1], gcd = _Gcd(Math.Abs(son), mom); var ans = (son / gcd) + "/" + (mom / gcd); if (p1 >= q1) ans = $"+{ans}"; return ans; diff --git a/cSharp-source/Solution/2-External/MathSection/DayQuestion.cs b/cSharp-source/Solution/2-External/MathSection/DayQuestion.cs new file mode 100644 index 0000000..7b4337c --- /dev/null +++ b/cSharp-source/Solution/2-External/MathSection/DayQuestion.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MathSection; +public class DayQuestion +{ + #region day 7.29 + + //593. Valid Square + //Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square. + //The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order. + //A valid square has four equal sides with positive length and four equal angles (90-degree angles). + public bool ValidSquare(int[] p1, int[] p2, int[] p3, int[] p4) + { + throw new NotImplementedException(); + } + + #endregion +} diff --git a/cSharp-source/Solution/2-External/MathSection/MathSection.csproj b/cSharp-source/Solution/2-External/MathSection/MathSection.csproj new file mode 100644 index 0000000..74abf5c --- /dev/null +++ b/cSharp-source/Solution/2-External/MathSection/MathSection.csproj @@ -0,0 +1,10 @@ + + + + Exe + net6.0 + enable + enable + + + diff --git a/cSharp-source/Solution/2-External/MathSection/Program.cs b/cSharp-source/Solution/2-External/MathSection/Program.cs new file mode 100644 index 0000000..837131c --- /dev/null +++ b/cSharp-source/Solution/2-External/MathSection/Program.cs @@ -0,0 +1 @@ +Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/Solution.sln b/cSharp-source/Solution/Solution.sln index f28aefd..6e3bd36 100644 --- a/cSharp-source/Solution/Solution.sln +++ b/cSharp-source/Solution/Solution.sln @@ -14,27 +14,29 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution .editorconfig = .editorconfig EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AlgorithmTest", "0-Test\AlgorithmTest\AlgorithmTest.csproj", "{6341CEA4-1D22-4330-984A-28C5C9F1A102}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AlgorithmTest", "0-Test\AlgorithmTest\AlgorithmTest.csproj", "{6341CEA4-1D22-4330-984A-28C5C9F1A102}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArraySection", "1-Basic\ArraySection\ArraySection.csproj", "{94FD5CF4-A049-45FD-ADBC-15DDBE88A796}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ArraySection", "1-Basic\ArraySection\ArraySection.csproj", "{94FD5CF4-A049-45FD-ADBC-15DDBE88A796}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LinkSection", "1-Basic\LinkSection\LinkSection.csproj", "{1423494B-2F5D-481D-AA50-1F2D965394DE}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LinkSection", "1-Basic\LinkSection\LinkSection.csproj", "{1423494B-2F5D-481D-AA50-1F2D965394DE}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QueueSection", "1-Basic\QueueSection\QueueSection.csproj", "{9DB66097-4D62-4E8F-8531-3F44FB8B91D2}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QueueSection", "1-Basic\QueueSection\QueueSection.csproj", "{9DB66097-4D62-4E8F-8531-3F44FB8B91D2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StackSection", "1-Basic\StackSection\StackSection.csproj", "{26C5CAF2-FDFD-48C4-97C8-1214AC963D8D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StackSection", "1-Basic\StackSection\StackSection.csproj", "{26C5CAF2-FDFD-48C4-97C8-1214AC963D8D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StringSection", "1-Basic\StringSection\StringSection.csproj", "{AF63F2C5-34DC-4E7B-8B79-C6F3D7A0482D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StringSection", "1-Basic\StringSection\StringSection.csproj", "{AF63F2C5-34DC-4E7B-8B79-C6F3D7A0482D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TreeSection", "1-Basic\TreeSection\TreeSection.csproj", "{E8F30DCA-D2B4-41DC-8AB0-54A70EFC90DE}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TreeSection", "1-Basic\TreeSection\TreeSection.csproj", "{E8F30DCA-D2B4-41DC-8AB0-54A70EFC90DE}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DPSection", "2-External\DPSection\DPSection.csproj", "{C8DEE532-AAAA-40FC-962E-F21DAA6C8C6F}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DPSection", "2-External\DPSection\DPSection.csproj", "{C8DEE532-AAAA-40FC-962E-F21DAA6C8C6F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EncodeSection", "2-External\EncodeSection\EncodeSection.csproj", "{F001E030-28DE-4C40-B424-C9B50100FEC7}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EncodeSection", "2-External\EncodeSection\EncodeSection.csproj", "{F001E030-28DE-4C40-B424-C9B50100FEC7}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OrderSetSection", "2-External\OrderSetSection\OrderSetSection.csproj", "{35FD5694-B1B8-4FD5-8FA8-896243F99EAB}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OrderSetSection", "2-External\OrderSetSection\OrderSetSection.csproj", "{35FD5694-B1B8-4FD5-8FA8-896243F99EAB}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrieSection", "2-External\TrieSection\TrieSection.csproj", "{95F18BB5-F085-4CE2-86DC-2322CFF768A2}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TrieSection", "2-External\TrieSection\TrieSection.csproj", "{95F18BB5-F085-4CE2-86DC-2322CFF768A2}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MathSection", "2-External\MathSection\MathSection.csproj", "{966165B5-25B4-406E-A2F4-5F1B87E0F0BE}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -86,6 +88,10 @@ Global {95F18BB5-F085-4CE2-86DC-2322CFF768A2}.Debug|Any CPU.Build.0 = Debug|Any CPU {95F18BB5-F085-4CE2-86DC-2322CFF768A2}.Release|Any CPU.ActiveCfg = Release|Any CPU {95F18BB5-F085-4CE2-86DC-2322CFF768A2}.Release|Any CPU.Build.0 = Release|Any CPU + {966165B5-25B4-406E-A2F4-5F1B87E0F0BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {966165B5-25B4-406E-A2F4-5F1B87E0F0BE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {966165B5-25B4-406E-A2F4-5F1B87E0F0BE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {966165B5-25B4-406E-A2F4-5F1B87E0F0BE}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -102,6 +108,7 @@ Global {F001E030-28DE-4C40-B424-C9B50100FEC7} = {5D2E938C-2618-4DD9-A439-F193655266A0} {35FD5694-B1B8-4FD5-8FA8-896243F99EAB} = {5D2E938C-2618-4DD9-A439-F193655266A0} {95F18BB5-F085-4CE2-86DC-2322CFF768A2} = {5D2E938C-2618-4DD9-A439-F193655266A0} + {966165B5-25B4-406E-A2F4-5F1B87E0F0BE} = {5D2E938C-2618-4DD9-A439-F193655266A0} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B95AEA45-E93F-42C8-990A-4C410797B0C6} -- Gitee From 29d23af06ba30f899beb4e7b8ebc209b9f55c00b Mon Sep 17 00:00:00 2001 From: zhousl Date: Fri, 29 Jul 2022 15:03:01 +0800 Subject: [PATCH 13/31] =?UTF-8?q?[#update]=20=E5=BF=BD=E7=95=A5=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E7=94=9F=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.gitignore b/.gitignore index c23a0b3..cb3e21c 100644 --- a/.gitignore +++ b/.gitignore @@ -70,12 +70,20 @@ ipch/ *.psess *.vsp *.vspx +*.v2 +*.v1 +*.testlog +*.manifest +*.vsidx +*.lock # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper* +*.iml +*.xml # NCrunch *.ncrunch* -- Gitee From cbe504bf5df9cf5cf9a1b349235c6c42f2aebb14 Mon Sep 17 00:00:00 2001 From: zhousl Date: Mon, 1 Aug 2022 11:00:43 +0800 Subject: [PATCH 14/31] [#update] --- .../2-External/MathSection/DayQuestion.cs | 23 ++++- .../src/2-external/mathSection/dayQuestion.go | 85 +++++++++++++++++++ 2 files changed, 105 insertions(+), 3 deletions(-) create mode 100644 go-source/src/2-external/mathSection/dayQuestion.go diff --git a/cSharp-source/Solution/2-External/MathSection/DayQuestion.cs b/cSharp-source/Solution/2-External/MathSection/DayQuestion.cs index 7b4337c..9e39dff 100644 --- a/cSharp-source/Solution/2-External/MathSection/DayQuestion.cs +++ b/cSharp-source/Solution/2-External/MathSection/DayQuestion.cs @@ -13,10 +13,27 @@ public class DayQuestion //Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square. //The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order. //A valid square has four equal sides with positive length and four equal angles (90-degree angles). + + private int shortLens = -1; + public bool ValidSquare(int[] p1, int[] p2, int[] p3, int[] p4) { - throw new NotImplementedException(); - } + return _ValidTriangle(p1, p2, p3) && _ValidTriangle(p1, p2, p4) && _ValidTriangle(p2, p3, p4) && _ValidTriangle(p1, p3, p4); + } + + private bool _ValidTriangle(int[] a, int[] b, int[] c) + { + var l1 = (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]); + var l2 = (a[0] - c[0]) * (a[0] - c[0]) + (a[1] - c[1]) * (a[1] - c[1]); + var l3 = (b[0] - c[0]) * (b[0] - c[0]) + (b[1] - c[1]) * (b[1] - c[1]); + var isTri = (l1 == l2 && l1 + l2 == l3) || (l1 == l3 && l1 + l3 == l2) || (l2 == l3 && l2 + l3 == l1); + + if (!isTri) return false; + // 判断边的合法性 正方形边边相等 + if (shortLens == -1) shortLens = Math.Min(l1, l2); + else if (shortLens == 0 || shortLens != Math.Min(l1, l2)) return false; + return true; + } #endregion -} +} \ No newline at end of file diff --git a/go-source/src/2-external/mathSection/dayQuestion.go b/go-source/src/2-external/mathSection/dayQuestion.go new file mode 100644 index 0000000..52b5079 --- /dev/null +++ b/go-source/src/2-external/mathSection/dayQuestion.go @@ -0,0 +1,85 @@ +package mathSection + +//593. Valid Square +//Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square. +//The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order. +//A valid square has four equal sides with positive length and four equal angles (90-degree angles). +var itemExist = struct{}{} + +func validSquare(p1 []int, p2 []int, p3 []int, p4 []int) bool { + squareDis := make(map[int]struct{}) + squareDis[calDistance(p1, p2)] = itemExist + squareDis[calDistance(p1, p3)] = itemExist + squareDis[calDistance(p1, p4)] = itemExist + squareDis[calDistance(p2, p3)] = itemExist + squareDis[calDistance(p2, p4)] = itemExist + squareDis[calDistance(p3, p4)] = itemExist + + if _, samePoint := squareDis[0]; samePoint || len(squareDis) != 2 { + return false + } + return true +} + +func calDistance(a, b []int) int { + l1 := a[0] - b[0] + l2 := a[1] - b[1] + return l1*l1 + l2*l2 +} + +//952. Largest Component Size by Common Factor + +var fn []int + +func largestComponentSize(nums []int) int { + m := 0 + // 找到祖先 + for i := 0; i < len(nums); i++ { + m = max(m, nums[i]) + } + + fn = make([]int, m+1) + for i := 0; i < len(fn); i++ { + fn[i] = i + } + for _, v := range nums { + for i := 2; i*i <= v; i++ { + if v%i == 0 { + // 合并两个共因素 + merge(v, i) + merge(v, v/i) + } + } + } + + // 映射关系 + mp := make(map[int]int) + res := 0 + for i := 0; i < len(nums); i++ { + // tmp表示代表元素 + tmp := find(nums[i]) + mp[tmp]++ + res = max(res, mp[tmp]) + } + return res +} +func find(i int) int { + if fn[i] == i { + return i + } else { + fn[i] = find(fn[i]) + return fn[i] + } +} +func merge(x int, y int) { + if x == y { + return + } + fn[find(x)] = find(y) +} +func max(a, b int) int { + if b > a { + return b + } + return a +} -- Gitee From 4bf1f7f68e3ee903992be13095fb9ef5921b1364 Mon Sep 17 00:00:00 2001 From: zhousl Date: Mon, 1 Aug 2022 18:13:42 +0800 Subject: [PATCH 15/31] =?UTF-8?q?[#update]=20=E6=AF=8F=E6=97=A5=E4=B8=80?= =?UTF-8?q?=E9=A2=98=E6=8D=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1-Basic/LinkSection/DesignLink.cs | 73 +++++++++++ .../1-Basic/StringSection/DayQuestion.cs | 22 +++- .../1-Basic/TreeSection/DayQuestion.cs | 29 +++++ .../src/1-basic/linkSection/designLink.go | 113 ++++++++++++++++++ .../src/1-basic/linkSection/removeLink.go | 4 +- .../src/1-basic/stringSection/dayQuestion.go | 11 ++ .../src/1-basic/treeSection/dayQuestion.go | 25 ++++ 7 files changed, 274 insertions(+), 3 deletions(-) create mode 100644 cSharp-source/Solution/1-Basic/LinkSection/DesignLink.cs create mode 100644 go-source/src/1-basic/linkSection/designLink.go create mode 100644 go-source/src/1-basic/stringSection/dayQuestion.go diff --git a/cSharp-source/Solution/1-Basic/LinkSection/DesignLink.cs b/cSharp-source/Solution/1-Basic/LinkSection/DesignLink.cs new file mode 100644 index 0000000..bc80987 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/LinkSection/DesignLink.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +// ReSharper disable All +#pragma warning disable CS8625 +namespace LinkSection; + +public class MyNode +{ + public int val { get; set; } + public MyNode next { get; set; } + + public MyNode(int val, MyNode next = null) + { + this.val = val; + this.next = next; + } +} +public class MyLinkedList +{ + private int length; + private MyNode head; + public MyLinkedList() + { + length = 0; + head = new MyNode(0); + } + + public int Get(int index) + { + if (index < 0 || index >= length) return -1; + + var cur = head; + for (int i = 0; i < index + 1; i++) cur = cur.next; + return cur.val; + } + + public void AddAtHead(int val) + { + AddAtIndex(0, val); + } + + public void AddAtTail(int val) + { + AddAtIndex(length, val); + } + + public void AddAtIndex(int index, int val) + { + if (index > length) return; + if (index < 0) index = 0; + + var node = new MyNode(val); + var pre = head; + for (int i = 0; i < index; i++) pre = pre.next; + node.next = pre.next; + pre.next = node; + length++; + } + + public void DeleteAtIndex(int index) + { + if (index < 0 || index >= length) return; + + var cur = head; + for (int i = 0; i < index; i++) cur = cur.next; + cur.next = cur.next.next; + length--; + } +} diff --git a/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs index 7abff6d..d30e77f 100644 --- a/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs @@ -1,4 +1,6 @@ -namespace StringSection; +using System.Text; + +namespace StringSection; public class DayQuestion { @@ -64,4 +66,22 @@ public class DayQuestion private long _Gcd(long a, long b) => b == 0 ? a : _Gcd(b, a % b); #endregion + + #region + + //1374. Generate a String With Characters That Have Odd Counts + public string GenerateTheString(int n) + { + if (n == 1) return "z"; + + var sb = new StringBuilder(); + char a = 'z', b = 's', c = 'l'; + for (int i = 0; i < n - 1; i++) sb.Append(a); + + if (sb.Length % 2 == 0) sb.Replace(a, b, sb.Length - 1, 1); + sb.Append(c); + + return sb.ToString(); + } + #endregion } \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs index cc475a0..78d2bc9 100644 --- a/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs @@ -79,4 +79,33 @@ public class DayQuestion // 919. Complete Binary Tree Inserter #endregion + + #region + + //1161. Maximum Level Sum of a Binary Tree + //Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. + //Return the smallest level x such that the sum of all the values of nodes at level x is maximal. + public int MaxLevelSum(TreeNode root) + { + var queue = new Queue(); + int res = 1, num = int.MinValue, level = 1; + + queue.Enqueue(root); + while (queue.Any()) + { + int size = queue.Count, sum = 0; + while (size-- > 0) + { + var cur = queue.Dequeue(); + sum += cur.val; + if (cur.left != null) queue.Enqueue(cur.left); + if (cur.right != null) queue.Enqueue(cur.right); + } + if (sum > num) (res, num) = (level, sum); + level++; + } + return res; + } + + #endregion } diff --git a/go-source/src/1-basic/linkSection/designLink.go b/go-source/src/1-basic/linkSection/designLink.go new file mode 100644 index 0000000..94e33b5 --- /dev/null +++ b/go-source/src/1-basic/linkSection/designLink.go @@ -0,0 +1,113 @@ +package linkSection + +/* +这道题要搞清楚head节点和第一个节点的区别 +head节点其实是第0号节点 +*/ + +type Node struct { + val int //链表的值 + next *Node //指向下一个节点的指针 +} + +type MyLinkedList struct { + head *Node //虚拟头结点 + size int //定义链表的长度 +} + +func Constructor() MyLinkedList { + //将head节点的值设置为-1,指向空节点 + dummyHead := &Node{ + val: -1, + next: nil, + } + //将链表的的长度设置为1 + return MyLinkedList{head: dummyHead, size: 0} +} + +func (this *MyLinkedList) Get(index int) int { + //判断index是否合法 + if (index < 0) || (index > (this.size - 1)) { + return -1 + } + //查找操作 + var cur *Node = this.head //从head节点开始遍历 + for i := 0; i <= index; i++ { + cur = cur.next //第index节点其实是index+1 + } + return cur.val +} + +func (this *MyLinkedList) AddAtHead(Val int) { + //先创建一个新的节点 + var newNode *Node = &Node{val: Val, next: nil} + //将新节点指向第一个节点 + newNode.next = this.head.next + //然后在将头结点指向新的节点 + this.head.next = newNode + //然后将链表的长度加1 + this.size++ +} + +func (this *MyLinkedList) AddAtTail(Val int) { + //先创建一个新的节点 + var newNode *Node = &Node{val: Val, next: nil} + //创建一个当前节点,并将它指向head结点,可以说它就是head结点 + cur := this.head + //因为是插到结尾 + for cur.next != nil { + cur = cur.next + } + //此时的cur指向的是nil, 将新节点插入cur之后 + cur.next = newNode + this.size++ +} + +func (this *MyLinkedList) AddAtIndex(index int, Val int) { + //条件判断:题目要求 + //添加的下标大于链表的长度,无效 + if index > this.size { + return + } else if index == this.size { //如果 index 等于链表的长度,则该节点将附加到链表的末尾 + this.AddAtTail(Val) + return + } else if index < 0 { //如果index小于0,则在头部插入节点。 + index = 0 + } + //定义一个新节点 + var newNode *Node = &Node{val: Val, next: nil} + //定义一个当前节点,指向头结点 + cur := this.head + //在index节点之前index-1处停止 + for i := 0; i < index; i++ { + cur = cur.next + } + //cur.next->index + newNode.next = cur.next + cur.next = newNode + this.size++ +} + +func (this *MyLinkedList) DeleteAtIndex(index int) { + if index > this.size-1 || index < 0 { + return + } + //从head节点开始 + cur := this.head + for i := 0; i < index; i++ { + cur = cur.next + } + //将当前节点指向自已节点下一个节点的下一个节点 + cur.next = cur.next.next + this.size-- +} + +/** + * Your MyLinkedList object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Get(index); + * obj.AddAtHead(val); + * obj.AddAtTail(val); + * obj.AddAtIndex(index,val); + * obj.DeleteAtIndex(index); + */ diff --git a/go-source/src/1-basic/linkSection/removeLink.go b/go-source/src/1-basic/linkSection/removeLink.go index 84e40eb..66805f3 100644 --- a/go-source/src/1-basic/linkSection/removeLink.go +++ b/go-source/src/1-basic/linkSection/removeLink.go @@ -1,7 +1,7 @@ package linkSection -//Given the head of a linked list and an integer val, -//remove all the nodes of the linked list that has Node.val == val, and return the new head. +//Given the head of a linked list and an integer Val, +//remove all the nodes of the linked list that has Node.Val == Val, and return the new head. // ListNode Definition for singly-linked list. type ListNode struct { diff --git a/go-source/src/1-basic/stringSection/dayQuestion.go b/go-source/src/1-basic/stringSection/dayQuestion.go new file mode 100644 index 0000000..a480059 --- /dev/null +++ b/go-source/src/1-basic/stringSection/dayQuestion.go @@ -0,0 +1,11 @@ +package stringSection + +import "strings" + +//1374. Generate a String With Characters That Have Odd Counts +func generateTheString(n int) string { + if n&1 == 1 { + return strings.Repeat("z", n) + } + return strings.Repeat("s", n-1) + "l" +} diff --git a/go-source/src/1-basic/treeSection/dayQuestion.go b/go-source/src/1-basic/treeSection/dayQuestion.go index a1b47ba..ad55747 100644 --- a/go-source/src/1-basic/treeSection/dayQuestion.go +++ b/go-source/src/1-basic/treeSection/dayQuestion.go @@ -33,6 +33,31 @@ func largestValues(root *TreeNode) []int { return res } +//1161. Maximum Level Sum of a Binary Tree +//Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. +//Return the smallest level x such that the sum of all the values of nodes at level x is maximal. +func maxLevelSum(root *TreeNode) int { + ans, num, level, queue := 1, -int(1e9), 1, []*TreeNode{root} + for len(queue) > 0 { + size, sum := len(queue), 0 + for i := 0; i < size; i++ { + sum += queue[i].Val + if queue[i].Left != nil { + queue = append(queue, queue[i].Left) + } + if queue[i].Right != nil { + queue = append(queue, queue[i].Right) + } + } + if sum > num { + ans, num = level, sum + } + queue = queue[size:] + level++ + } + return ans +} + func max(a, b int) int { if a > b { return a -- Gitee From 864d1715d01fbaaf0e315efaca5c47e219739f1f Mon Sep 17 00:00:00 2001 From: zhousl Date: Tue, 2 Aug 2022 18:23:51 +0800 Subject: [PATCH 16/31] =?UTF-8?q?[#add]=20=E6=AF=8F=E6=97=A5=E7=AE=80?= =?UTF-8?q?=E5=8D=95=E4=B8=80=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1-Basic/QueueSection/DayQuestion.cs | 43 ++++++++++++++- .../circularQueue/myCircularQueue.go | 55 +++++++++++++++++++ 2 files changed, 96 insertions(+), 2 deletions(-) create mode 100644 go-source/src/1-basic/queueSection/circularQueue/myCircularQueue.go diff --git a/cSharp-source/Solution/1-Basic/QueueSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/QueueSection/DayQuestion.cs index 34c0c03..d70b91a 100644 --- a/cSharp-source/Solution/1-Basic/QueueSection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/QueueSection/DayQuestion.cs @@ -2,8 +2,11 @@ public class DayQuestion { + } +#region day 8.1 + // 剑指 Offer II 041. 滑动窗口的平均值 public class MovingAverage { @@ -13,7 +16,7 @@ public class MovingAverage /** Initialize your data structure here. */ public MovingAverage(int size) { - this.arr = new int [10010]; + this.arr = new int[10010]; this._size = size; } @@ -27,4 +30,40 @@ public class MovingAverage } return (double)sum / (rear - front); } -} \ No newline at end of file +} + +#endregion + +#region day 8.2 + +//622. Design Circular Queue +public class MyCircularQueue +{ + private int[] _myQueue; + private int _head, _tail, _length; + public MyCircularQueue(int k) + { + _length = k; + _myQueue = new int[_length]; + } + + public bool EnQueue(int value) + { + if (IsFull()) return false; + _myQueue[_tail % _length] = value; + return ++_tail >= 0; + } + + public bool DeQueue() + { + if (IsEmpty()) return false; + return ++_head >= 0; + } + + public int Front() => IsEmpty() ? -1 : _myQueue[_head % _length]; + public int Rear() => IsEmpty() ? -1 : _myQueue[(_tail - 1) % _length]; + public bool IsEmpty() => _head == _tail; + public bool IsFull() => (_tail - _head) == _length; +} + +#endregion \ No newline at end of file diff --git a/go-source/src/1-basic/queueSection/circularQueue/myCircularQueue.go b/go-source/src/1-basic/queueSection/circularQueue/myCircularQueue.go new file mode 100644 index 0000000..70a9237 --- /dev/null +++ b/go-source/src/1-basic/queueSection/circularQueue/myCircularQueue.go @@ -0,0 +1,55 @@ +package circularQueue + +type MyCircularQueue struct { + Head int + Tail int + Queue []int + Length int +} + +func Constructor(k int) MyCircularQueue { + return MyCircularQueue{0, 0, make([]int, k), k} +} + +func (this *MyCircularQueue) EnQueue(value int) bool { + if this.IsFull() { + return false + } else { + this.Queue[this.Tail%this.Length] = value + this.Tail++ + return this.Tail >= 0 + } +} + +func (this *MyCircularQueue) DeQueue() bool { + if this.IsEmpty() { + return false + } else { + this.Head++ + return this.Head >= 0 + } +} + +func (this *MyCircularQueue) Front() int { + if this.IsEmpty() { + return -1 + } else { + return this.Queue[this.Head%this.Length] + } +} + +func (this *MyCircularQueue) Rear() int { + if this.IsEmpty() { + return -1 + } else { + return this.Queue[(this.Tail-1)%this.Length] + } +} + +func (this *MyCircularQueue) IsEmpty() bool { + return this.Head == this.Tail +} + +func (this *MyCircularQueue) IsFull() bool { + return this.Tail-this.Head == this.Length +} -- Gitee From c24c435d82a6e3f8d41dccfb319514b6e8023df3 Mon Sep 17 00:00:00 2001 From: zhousl Date: Thu, 4 Aug 2022 11:13:05 +0800 Subject: [PATCH 17/31] =?UTF-8?q?[#update]=20=E6=98=A8=E5=A4=A9=E7=9A=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0-Test/AlgorithmTest/ArrayTest.cs | 1 + .../1-Basic/LinkSection/LinkSection.csproj | 8 ++++ .../1-Basic/LinkSection/ReverseLink.cs | 33 ++++++++++++++++ .../2-External/OrderSetSection/OrderQueue.cs | 39 +++++++++++++++++++ .../2-external/orderSetSection/orderQueue.go | 24 ++++++++++++ 5 files changed, 105 insertions(+) create mode 100644 cSharp-source/Solution/1-Basic/LinkSection/ReverseLink.cs create mode 100644 cSharp-source/Solution/2-External/OrderSetSection/OrderQueue.cs create mode 100644 go-source/src/2-external/orderSetSection/orderQueue.go diff --git a/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs b/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs index b114213..1052c63 100644 --- a/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs @@ -14,6 +14,7 @@ public class ArrayTest { var ans = _Gcd(12, 25); _outputHelper.WriteLine(ans.ToString()); + Monitor.Wait } [Fact] diff --git a/cSharp-source/Solution/1-Basic/LinkSection/LinkSection.csproj b/cSharp-source/Solution/1-Basic/LinkSection/LinkSection.csproj index b9de063..2c6cde9 100644 --- a/cSharp-source/Solution/1-Basic/LinkSection/LinkSection.csproj +++ b/cSharp-source/Solution/1-Basic/LinkSection/LinkSection.csproj @@ -7,4 +7,12 @@ enable + + 1701;1702;8600;8601 + + + + 1701;1702;8600;8601 + + diff --git a/cSharp-source/Solution/1-Basic/LinkSection/ReverseLink.cs b/cSharp-source/Solution/1-Basic/LinkSection/ReverseLink.cs new file mode 100644 index 0000000..c824ac7 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/LinkSection/ReverseLink.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LinkSection; +public class ReverseLink +{ + #region day 8.3 + + //206. Reverse Linked List + //Given the head of a singly linked list, reverse the list, and return the reversed list. + public ListNode ReverseList(ListNode head) + { + if (head == null) return head; + + ListNode temp; + ListNode pre = null; + ListNode cur = head; + + while (cur != null) + { + temp = cur.next; + cur.next = pre; + pre = cur; + cur = temp; + } + return pre; + } + + #endregion +} diff --git a/cSharp-source/Solution/2-External/OrderSetSection/OrderQueue.cs b/cSharp-source/Solution/2-External/OrderSetSection/OrderQueue.cs new file mode 100644 index 0000000..d80e052 --- /dev/null +++ b/cSharp-source/Solution/2-External/OrderSetSection/OrderQueue.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrderSetSection; +public class OrderQueue +{ + #region day 8.3 + + //You are given a string s and an integer k.You can choose one of the first k letters of s and append it at the end of the string.. + //Return the lexicographically smallest string you could have after applying the mentioned step any number of moves. + //"cba" -> "acb" + public string OrderlyQueue(string s, int k) + { + if (string.IsNullOrEmpty(s)) return s; + + if (k > 1) + { + char[] chs = s.ToCharArray(); + Array.Sort(chs); + return new string(chs); + } + + var smallest = s; + for (int i = 0; i < s.Length; i++) + { + var first = s[0]; + s = s.Remove(0, 1); + s += first; + + if (smallest.CompareTo(s) > 0) smallest = s; + } + return smallest; + } + + #endregion +} diff --git a/go-source/src/2-external/orderSetSection/orderQueue.go b/go-source/src/2-external/orderSetSection/orderQueue.go new file mode 100644 index 0000000..7f4a689 --- /dev/null +++ b/go-source/src/2-external/orderSetSection/orderQueue.go @@ -0,0 +1,24 @@ +package orderSetSection + +import "sort" + +//You are given a string s and an integer k.You can choose one of the first k letters of s and append it at the end of the string.. +//Return lexicographically the smallest string you could have after applying the mentioned step any number of moves. +func orderlyQueue(s string, k int) string { + if k > 1 { + bytes := []byte(s) + sort.Slice(bytes, func(i, j int) bool { + return bytes[i] < bytes[j] + }) + return string(bytes) + } else { + ans := s + for i := 0; i < len(s); i++ { + cur := s[i:] + s[:i] + if cur < ans { + ans = cur + } + } + return ans + } +} -- Gitee From 716474284b770622c31b37b7e4ba61201484a8a7 Mon Sep 17 00:00:00 2001 From: zhousl Date: Thu, 4 Aug 2022 16:06:29 +0800 Subject: [PATCH 18/31] =?UTF-8?q?[#add]=20=E6=AF=8F=E6=97=A5=E4=B8=80?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1-Basic/ArraySection/DayQuestion.cs | 42 +++++++++++++++- .../src/1-basic/arraySection/dayQuestion.go | 48 ++++++++++++------- 2 files changed, 73 insertions(+), 17 deletions(-) diff --git a/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs index 18c72fd..f15305c 100644 --- a/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs @@ -346,7 +346,7 @@ public class DayQuestion //1331. Rank Transform of an Array public int[] ArrayRankTransform(int[] arr) { - var sortArr = new int[arr.Length]; + var sortArr = new int[arr.Length]; Array.Copy(arr, sortArr, arr.Length); Array.Sort(sortArr); @@ -362,4 +362,44 @@ public class DayQuestion } #endregion + + #region 8.4 + + + /* 1403. Minimum Subsequence in Non-Increasing Order + * Given the array nums + * obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. + * + * If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, + * return the subsequence with the maximum total sum of all its elements. + * + * A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. + * Note that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order. + * + * Input: nums = [4,3,10,9,8] + * Output: [10,9] + * Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included, + * however, the subsequence [10,9] has the maximum total sum of its elements.  + * + * Constraints: + * 1 <= nums.length <= 500 + * 1 <= nums[i] <= 100 + */ + public IList MinSubsequence(int[] nums) + { + IList res = new List(); + int sum = nums.Sum(), cur = 0, index = nums.Length - 1; + + Array.Sort(nums); + while (cur <= sum) + { + cur += nums[index]; + sum -= nums[index]; + res.Add(nums[index]); + index--; + } + return res; + } + + #endregion } \ No newline at end of file diff --git a/go-source/src/1-basic/arraySection/dayQuestion.go b/go-source/src/1-basic/arraySection/dayQuestion.go index bebb75c..e81fd13 100644 --- a/go-source/src/1-basic/arraySection/dayQuestion.go +++ b/go-source/src/1-basic/arraySection/dayQuestion.go @@ -7,28 +7,16 @@ import ( /* Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. - A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: 0 <= i, j < nums.length i != j nums[i] - nums[j] == k Notice that |val| denotes the absolute value of val. - Example 1: Input: nums = [3,1,4,1,5], k = 2 Output: 2 Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of unique pairs. - -Example 2: -Input: nums = [1,2,3,4,5], k = 1 -Output: 4 -Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). - -Example 3: -Input: nums = [1,3,1,5,4], k = 0 -Output: 1 -Explanation: There is one 0-diff pair in the array, (1, 1). */ func findPairs(nums []int, k int) int { if k < 0 { @@ -149,10 +137,6 @@ Example 1: Input: nums = [1,5,1,1,6,4] Output: [1,6,1,5,1,4] Explanation: [1,4,1,5,1,6] is also accepted. - -Example 2: -Input: nums = [1, 3, 2, 2, 3, 1] -Output: [2,3,1,3,1,2] */ func wiggleSort(nums []int) { n := len(nums) @@ -196,3 +180,35 @@ func arrayNesting(nums []int) int { } return res } + +/* 1403. Minimum Subsequence in Non-Increasing Order + * Given the array nums + * obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the not included elements in such subsequence. + * + * If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, + * return the subsequence with the maximum total sum of all its elements. + * + * A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. + * Note that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order. + * + * Input: nums = [4,3,10,9,8] + * Output: [10,9] + * Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included, + * however, the subsequence [10,9] has the maximum total sum of its elements. + */ +func minSubsequence(nums []int) []int { + var sum, cur, index = 0, 0, len(nums) - 1 + var res []int + for i := 0; i < len(nums); i++ { + sum += nums[i] + } + sort.Ints(nums) + + for cur <= sum { + cur += nums[index] + sum -= nums[index] + res = append(res, nums[index]) + index-- + } + return res +} -- Gitee From d1d82a7486723d65c0cca57afdb27f9d42291d19 Mon Sep 17 00:00:00 2001 From: zhousl Date: Tue, 9 Aug 2022 18:51:57 +0800 Subject: [PATCH 19/31] =?UTF-8?q?[#add]=20=E6=AF=8F=E6=97=A5=E4=B8=80?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Solution/0-Test/AlgorithmTest/TreeTest.cs | 15 +++++ .../Solution/0-Test/AlgorithmTest/Usings.cs | 1 + .../1-Basic/ArraySection/DayQuestion.cs | 23 +++++++- .../1-Basic/StackSection/DayQuestions.cs | 35 +++++++++++- .../1-Basic/TreeSection/DayQuestion.cs | 57 ++++++++++++++++--- .../1-Basic/TreeSection/TreeSection.csproj | 4 +- .../src/1-basic/stackSection/dayQuestion.go | 32 +++++++++++ .../2-external/encodeSection/dayQuestion.go | 2 +- .../recursionSection/dayQuestion.go | 33 +++++++++++ 9 files changed, 190 insertions(+), 12 deletions(-) create mode 100644 cSharp-source/Solution/0-Test/AlgorithmTest/TreeTest.cs create mode 100644 go-source/src/1-basic/stackSection/dayQuestion.go create mode 100644 go-source/src/2-external/recursionSection/dayQuestion.go diff --git a/cSharp-source/Solution/0-Test/AlgorithmTest/TreeTest.cs b/cSharp-source/Solution/0-Test/AlgorithmTest/TreeTest.cs new file mode 100644 index 0000000..6fb0b4c --- /dev/null +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/TreeTest.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TestSolution; +public class TreeTest +{ + [Fact] + public void AddOneRow_Test() + { + + } +} diff --git a/cSharp-source/Solution/0-Test/AlgorithmTest/Usings.cs b/cSharp-source/Solution/0-Test/AlgorithmTest/Usings.cs index fda36ad..9a7b58c 100644 --- a/cSharp-source/Solution/0-Test/AlgorithmTest/Usings.cs +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/Usings.cs @@ -1,4 +1,5 @@ global using Xunit; global using ArraySection; global using StringSection; +global using TreeSection; global using Xunit.Abstractions; \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs index f15305c..0a473aa 100644 --- a/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs @@ -363,7 +363,7 @@ public class DayQuestion #endregion - #region 8.4 + #region day 8.4 /* 1403. Minimum Subsequence in Non-Increasing Order @@ -402,4 +402,25 @@ public class DayQuestion } #endregion + + #region day 8.9 + + /* 1413. Minimum Value to Get Positive Step by Step Sum + * + * Given an array of integers nums, you start with an initial positive value startValue. + * In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right). + * Return the minimum positive value of startValue such that the step by step sum is never less than 1. + */ + public int MinStartValue(int[] nums) + { + int min = 0, cur = 0; + for (int i = 0; i < nums.Length; i++) + { + cur += nums[i]; + min = Math.Min(min, cur); + } + return -min + 1; + } + + #endregion } \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/StackSection/DayQuestions.cs b/cSharp-source/Solution/1-Basic/StackSection/DayQuestions.cs index ee4b3b1..2cf6e03 100644 --- a/cSharp-source/Solution/1-Basic/StackSection/DayQuestions.cs +++ b/cSharp-source/Solution/1-Basic/StackSection/DayQuestions.cs @@ -44,6 +44,39 @@ public class DayQuestions } return res; } - + + #endregion + + #region day 8.8 + + public int[] ExclusiveTime(int n, IList logs) + { + var res = new int[n]; + var totalTime = 0; + var funcStack = new Stack>(); + + foreach (var log in logs) + { + var spilits = log.Split(':'); + var funcId = Convert.ToInt32(spilits[0]); + var funcOpTime = Convert.ToInt32(spilits[2]); + + if (spilits[1].Equals("start")) + { + funcStack.Push(new List { funcOpTime, totalTime }); + } + else + { + var lastFunc = funcStack.Pop(); + var runTime = funcOpTime + 1 - lastFunc[0]; // 开始到结束时间 + var lockTime = totalTime - lastFunc[1]; // 独占时间 + var diff = runTime - lockTime; + res[funcId] += diff; + totalTime += diff; + } + } + return res; + } + #endregion } \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs index 78d2bc9..39a82ba 100644 --- a/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs @@ -74,13 +74,7 @@ public class DayQuestion #endregion - #region day 7.25 - - // 919. Complete Binary Tree Inserter - - #endregion - - #region + #region day 7.29 //1161. Maximum Level Sum of a Binary Tree //Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. @@ -108,4 +102,53 @@ public class DayQuestion } #endregion + + #region day 8.2 + + /* 623. Add One Row to Tree + * Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth. + * Note that the root node is at depth 1. + * + * Constraints: + * The number of nodes in the tree is in the range [1, 104]. + * The depth of the tree is in the range [1, 104]. + * -100 <= Node.val <= 100 + * -105 <= val <= 105 + * 1 <= depth <= the depth of tree + 1 + */ + public TreeNode AddOneRow(TreeNode root, int val, int depth) + { + if (depth == 1) + { + var tree = new TreeNode(val, root); + return tree; + } + + Queue queue = new Queue(); + queue.Enqueue(root); + + int curDepth = 1; + while (curDepth < depth - 1) + { + var temp = new Queue(); + while (queue.Any()) + { + var node = queue.Dequeue(); + if (node.left != null) temp.Enqueue(node.left); + if (node.right != null) temp.Enqueue(node.right); + } + queue = temp; + curDepth++; + } + + while (queue.Any()) + { + var depthNode = queue.Dequeue(); + depthNode.left = new TreeNode(val, depthNode.left, null); + depthNode.right = new TreeNode(val, null, depthNode.right); + } + return root; + } + + #endregion } diff --git a/cSharp-source/Solution/1-Basic/TreeSection/TreeSection.csproj b/cSharp-source/Solution/1-Basic/TreeSection/TreeSection.csproj index a91a69e..d33f8bd 100644 --- a/cSharp-source/Solution/1-Basic/TreeSection/TreeSection.csproj +++ b/cSharp-source/Solution/1-Basic/TreeSection/TreeSection.csproj @@ -8,11 +8,11 @@ - 1701;1702;8600 + 1701;1702;8600;8650 - 1701;1702;8600 + 1701;1702;8600;8650 diff --git a/go-source/src/1-basic/stackSection/dayQuestion.go b/go-source/src/1-basic/stackSection/dayQuestion.go new file mode 100644 index 0000000..4343eba --- /dev/null +++ b/go-source/src/1-basic/stackSection/dayQuestion.go @@ -0,0 +1,32 @@ +package stackSection + +import ( + "strconv" + "strings" +) + +// 636. Exclusive Time of Functions + +func exclusiveTime(n int, logs []string) []int { + var stack [][]int + ans, totalTime := make([]int, n), 0 + + for _, log := range logs { + splits := strings.Split(log, ":") + funcId, _ := strconv.Atoi(splits[0]) + funcOpTime, _ := strconv.Atoi(splits[2]) + // 入栈 + if splits[1] == "start" { + stack = append(stack, []int{funcOpTime, totalTime}) + } else { + lastFunc := stack[len(stack)-1] + stack = stack[:len(stack)-1] + + // lastFunc[0]方法开始时间 lastFunc[1]减去中间被占用的独立时间 + diff := (funcOpTime + 1 - lastFunc[0]) - (totalTime - lastFunc[1]) + ans[funcId] += diff + totalTime += diff + } + } + return ans +} diff --git a/go-source/src/2-external/encodeSection/dayQuestion.go b/go-source/src/2-external/encodeSection/dayQuestion.go index 69fcbcc..7b34d61 100644 --- a/go-source/src/2-external/encodeSection/dayQuestion.go +++ b/go-source/src/2-external/encodeSection/dayQuestion.go @@ -7,7 +7,7 @@ import ( // 535. Encode and Decode TinyURL // TinyURL is a URL shortening service where you enter a URL such as -// https:leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. +// https:leetcode.com/problems/design-tinyurl, and it returns a short URL such as http://tinyurl.com/4e9iAk. // Design a class to encode a URL and decode a tiny URL. // There is no restriction on how your encode/decode algorithm should work. // You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. diff --git a/go-source/src/2-external/recursionSection/dayQuestion.go b/go-source/src/2-external/recursionSection/dayQuestion.go new file mode 100644 index 0000000..8c33b10 --- /dev/null +++ b/go-source/src/2-external/recursionSection/dayQuestion.go @@ -0,0 +1,33 @@ +package recursionSection + +import ( + "sort" + "strings" +) + +/* +761. Special Binary String +Special binary strings are binary strings with the following two properties: +The number of 0's is equal to the number of 1's. +Every prefix of the binary string has at least as many 1's as 0's. +You are given a special binary string s. +A move consists of choosing two consecutive, non-empty, special substrings of s, and swapping them. +Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string. +Return the lexicographically largest resulting string possible after applying the mentioned operations on the string. +*/ +func makeLargestSpecial(s string) string { + candidates := sort.StringSlice{} + for i, cur, last := 0, 0, 0; i < len(s); i++ { + if s[i] == '1' { + cur++ + } else { + cur-- + } + if cur == 0 { + candidates = append(candidates, "1"+makeLargestSpecial(s[last+1:i])+"0") + last = i + 1 + } + } + sort.Sort(sort.Reverse(candidates)) + return strings.Join(candidates, "") +} -- Gitee From e60869d64f720bfeac2b28bcf3083762cee57e7c Mon Sep 17 00:00:00 2001 From: zhousl Date: Wed, 10 Aug 2022 17:58:48 +0800 Subject: [PATCH 20/31] =?UTF-8?q?[#add]=20=E6=AF=8F=E6=97=A5=E4=B8=80?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0-Test/AlgorithmTest/ArrayTest.cs | 9 ++- .../0-Test/AlgorithmTest/StringTest.cs | 9 +++ .../1-Basic/StringSection/DayQuestion.cs | 67 ++++++++++++++++++- .../src/1-basic/stackSection/dayQuestion.go | 1 - .../src/1-basic/stringSection/dayQuestion.go | 65 +++++++++++++++++- 5 files changed, 143 insertions(+), 8 deletions(-) diff --git a/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs b/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs index 1052c63..a41e655 100644 --- a/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs @@ -8,15 +8,14 @@ public class ArrayTest { _outputHelper = outputHelper; } - + [Fact] public void Test() { var ans = _Gcd(12, 25); _outputHelper.WriteLine(ans.ToString()); - Monitor.Wait } - + [Fact] public void Test_Parse() { @@ -24,9 +23,9 @@ public class ArrayTest _outputHelper.WriteLine(ans[0].ToString()); _outputHelper.WriteLine(ans[1].ToString()); } - + private long _Gcd(long a, long b) => b == 0 ? a : _Gcd(b, a % b); - + private long[] _Parse(string s) { int idx = 1; // 去除符号 diff --git a/cSharp-source/Solution/0-Test/AlgorithmTest/StringTest.cs b/cSharp-source/Solution/0-Test/AlgorithmTest/StringTest.cs index bd411ca..9aaadba 100644 --- a/cSharp-source/Solution/0-Test/AlgorithmTest/StringTest.cs +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/StringTest.cs @@ -18,4 +18,13 @@ public class StringTest var ans = invoker.FractionAddition(parameters); _outputHelper.WriteLine(ans.ToString()); } + + [Fact] + public void Test_SolveEquation() + { + var invoker = new DayQuestion(); + var parameters = "x+5-3+x=6+x-2"; + var ans = invoker.SolveEquation(parameters); + _outputHelper.WriteLine(ans.ToString()); + } } diff --git a/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs index d30e77f..9f9cc0a 100644 --- a/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs @@ -67,7 +67,7 @@ public class DayQuestion #endregion - #region + #region day 7.29 //1374. Generate a String With Characters That Have Odd Counts public string GenerateTheString(int n) @@ -84,4 +84,69 @@ public class DayQuestion return sb.ToString(); } #endregion + + #region day 8.10 + + /* + 640. Solve the Equation + Solve a given equation and return the value of 'x' in the form of a string "x=#value". + The equation contains only '+', '-' operation, the variable 'x' and its coefficient. + You should return "No solution" if there is no solution for the equation, or "Infinite solutions" + if there are infinite solutions for the equation. + If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer. + */ + private int _xSum; + private int _valueSum; + + public string SolveEquation(string equation) + { + string[] splits = equation.Split('='); + ParseString(splits[0], 1); + ParseString(splits[1], -1); + + // 全部移到右边 + if (_xSum == 0) return _valueSum == 0 ? "Infinite solutions" : "No solution"; + return $"x={-_valueSum / _xSum}"; + } + + private void ParseString(string s, int sign) + { + int idx = 0, curSign = 1; + while (idx < s.Length) + { + char c = s[idx]; + if (c == 'x') + { + if (sign * curSign == 1) _xSum++; + else _xSum--; + idx++; + } + else if (c == '-' || c == '+') + { + curSign = c == '-' ? -1 : 1; + idx++; + } + else + { + int curNum; + var temp = new StringBuilder(); + while (idx < s.Length && char.IsDigit(s[idx])) + { + temp.Append(s[idx]); + idx++; + } + curNum = Convert.ToInt32(temp.ToString()) * curSign * sign; + + if (idx < s.Length && s[idx] == 'x') + { + _xSum += curNum; + idx++; + } + else + _valueSum += curNum; + } + } + } + + #endregion } \ No newline at end of file diff --git a/go-source/src/1-basic/stackSection/dayQuestion.go b/go-source/src/1-basic/stackSection/dayQuestion.go index 4343eba..61c4110 100644 --- a/go-source/src/1-basic/stackSection/dayQuestion.go +++ b/go-source/src/1-basic/stackSection/dayQuestion.go @@ -6,7 +6,6 @@ import ( ) // 636. Exclusive Time of Functions - func exclusiveTime(n int, logs []string) []int { var stack [][]int ans, totalTime := make([]int, n), 0 diff --git a/go-source/src/1-basic/stringSection/dayQuestion.go b/go-source/src/1-basic/stringSection/dayQuestion.go index a480059..2324095 100644 --- a/go-source/src/1-basic/stringSection/dayQuestion.go +++ b/go-source/src/1-basic/stringSection/dayQuestion.go @@ -1,6 +1,9 @@ package stringSection -import "strings" +import ( + "strconv" + "strings" +) //1374. Generate a String With Characters That Have Odd Counts func generateTheString(n int) string { @@ -9,3 +12,63 @@ func generateTheString(n int) string { } return strings.Repeat("s", n-1) + "l" } + +/* +640. Solve the Equation +Solve a given equation and return the value of 'x' in the form of a string "x=#value". +The equation contains only '+', '-' operation, the variable 'x' and its coefficient. +You should return "No solution" if there is no solution for the equation, or "Infinite solutions" +if there are infinite solutions for the equation. +If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer. +*/ +func solveEquation(equation string) string { + equation += "=" + sign, cur, num, k, left, hasVal := 1, 0, 0, 0, true, false + for i := 0; i < len(equation); i++ { + if equation[i] == '-' { + if !left { + num += sign * cur + } else { + num -= sign * cur + } + cur, hasVal, sign = 0, false, -1 + } else if equation[i] == '+' { + if !left { + num += sign * cur + } else { + num -= sign * cur + } + cur, hasVal, sign = 0, false, 1 + } else if equation[i] == '=' { + if !left { + num += sign * cur + } else { + num -= sign * cur + } + cur, hasVal, sign, left = 0, false, 1, false + } else if equation[i] == 'x' { + if !hasVal && cur == 0 { + cur = 1 + } + if left { + k += sign * cur + } else { + k -= sign * cur + } + cur, hasVal = 0, false + } else { + hasVal = true + cur = cur*10 + int(equation[i]-'0') + } + } + if k == 0 { + if num != 0 { + return "No solution" + } + return "Infinite solutions" + } + if num%k == 0 { + return "x=" + strconv.Itoa(num/k) + } + return "No solution" +} -- Gitee From 80d2c8f6451ca42a9eb66079fe1d096fa273ec09 Mon Sep 17 00:00:00 2001 From: zhousl Date: Wed, 10 Aug 2022 17:58:56 +0800 Subject: [PATCH 21/31] =?UTF-8?q?=E3=80=90#update=E3=80=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index cb3e21c..58b35fc 100644 --- a/.gitignore +++ b/.gitignore @@ -71,6 +71,7 @@ ipch/ *.vsp *.vspx *.v2 +*.v5 *.v1 *.testlog *.manifest -- Gitee From d642e0e105234721ebeafb1b8d59987a2bb99694 Mon Sep 17 00:00:00 2001 From: zhousl Date: Thu, 11 Aug 2022 17:34:34 +0800 Subject: [PATCH 22/31] =?UTF-8?q?[#add]=20=E6=AF=8F=E6=97=A5=E4=B8=80?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1-Basic/StringSection/DayQuestion.cs | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs index 9f9cc0a..0755c1b 100644 --- a/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs @@ -149,4 +149,40 @@ public class DayQuestion } #endregion + + #region day 8.11 + + /* + 1417. Reformat The String + You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). + You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. + That is, no two adjacent characters have the same type. + Return the reformatted string or return an empty string if it is impossible to reformat the string. + */ + public string Reformat(string s) + { + StringBuilder d = new StringBuilder(), l = new StringBuilder(); + for (int i = 0; i < s.Length; i++) + { + if (s[i] >= 'a') l.Append(s[i]); + else d.Append(s[i]); + } + int n = d.Length, m = l.Length, end = m + n; + if (Math.Abs(n - m) > 1) return ""; + + var res = new StringBuilder(); + while (res.Length != end) + { + if (n > m) res.Append(d[--n]); + else if (n < m) res.Append(l[--m]); + else + { + if (res.Length != 0 && res[res.Length - 1] >= 'a') res.Append(d[--n]); + else res.Append(l[--m]); + } + } + return res.ToString(); + } + + #endregion } \ No newline at end of file -- Gitee From c1fa7762546b3ee4fb6a9b60821f0c6275dc67d9 Mon Sep 17 00:00:00 2001 From: zhousl Date: Mon, 15 Aug 2022 16:11:05 +0800 Subject: [PATCH 23/31] =?UTF-8?q?[#update]=20=E6=AF=8F=E6=97=A5=E4=B8=80?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0-Test/AlgorithmTest/StringTest.cs | 9 +++ .../1-Basic/ArraySection/DayQuestion.cs | 70 ++++++++++++++++--- .../1-Basic/QueueSection/MyCircularDeque.cs | 62 ++++++++++++++++ .../1-Basic/StringSection/DayQuestion.cs | 29 ++++++++ .../src/1-basic/arraySection/dayQuestion.go | 21 ++++++ .../src/1-basic/stringSection/dayQuestion.go | 21 ++++++ go-source/src/main.go | 29 +++----- 7 files changed, 213 insertions(+), 28 deletions(-) create mode 100644 cSharp-source/Solution/1-Basic/QueueSection/MyCircularDeque.cs diff --git a/cSharp-source/Solution/0-Test/AlgorithmTest/StringTest.cs b/cSharp-source/Solution/0-Test/AlgorithmTest/StringTest.cs index 9aaadba..77dfce5 100644 --- a/cSharp-source/Solution/0-Test/AlgorithmTest/StringTest.cs +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/StringTest.cs @@ -27,4 +27,13 @@ public class StringTest var ans = invoker.SolveEquation(parameters); _outputHelper.WriteLine(ans.ToString()); } + + [Fact] + public void Test_MaxScore() + { + var invoker = new DayQuestion(); + var parameters = "011101"; + var ans = invoker.MaxScore(parameters); + _outputHelper.WriteLine(ans.ToString()); + } } diff --git a/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs index 0a473aa..d9cc21e 100644 --- a/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs @@ -122,12 +122,13 @@ public class DayQuestion sb.Append(t); if (t == '.') sb.Append(']'); } + return sb.ToString(); } #endregion - #region day 6.23 + #region day 6.23 // 30. Substring with Concatenation of All Words // You are given a string s and an array of strings words of the same length. @@ -150,6 +151,7 @@ public class DayQuestion { break; } + Dictionary differ = new Dictionary(); for (int j = 0; j < m; j++) { @@ -158,20 +160,24 @@ public class DayQuestion { differ.Add(word, 0); } + differ[word]++; } + foreach (string word in words) { if (!differ.ContainsKey(word)) { differ.Add(word, 0); } + differ[word]--; if (differ[word] == 0) { differ.Remove(word); } } + for (int start = i; start < ls - m * n + 1; start += n) { if (start != i) @@ -181,28 +187,33 @@ public class DayQuestion { differ.Add(word, 0); } + differ[word]++; if (differ[word] == 0) { differ.Remove(word); } + word = s.Substring(start - n, n); if (!differ.ContainsKey(word)) { differ.Add(word, 0); } + differ[word]--; if (differ[word] == 0) { differ.Remove(word); } } + if (differ.Count == 0) { res.Add(start); } } } + return res; } @@ -233,10 +244,12 @@ public class DayQuestion { st1.Push(nums[idx++]); } + while (idx < nums.Length) { st2.Push(nums[idx++]); } + bool flag = true; idx = 0; while (st1.Count > 0 || st2.Count > 0) @@ -261,14 +274,16 @@ public class DayQuestion int b = position[j]; cur += Math.Abs(a - b) % 2; } + ans = Math.Min(ans, cur); } + return ans; } #endregion - #region day 7.18 + #region day 7.18 // 565. Array Nesting public int ArrayNesting(int[] nums) @@ -294,8 +309,10 @@ public class DayQuestion len++; next = nums[next]; } + res = len > res ? len : res; } + return res; } @@ -336,6 +353,7 @@ public class DayQuestion ans++; } } + return ans; } @@ -365,7 +383,6 @@ public class DayQuestion #region day 8.4 - /* 1403. Minimum Subsequence in Non-Increasing Order * Given the array nums * obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. @@ -379,7 +396,7 @@ public class DayQuestion * Input: nums = [4,3,10,9,8] * Output: [10,9] * Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included, - * however, the subsequence [10,9] has the maximum total sum of its elements.  + * however, the subsequence [10,9] has the maximum total sum of its elements. * * Constraints: * 1 <= nums.length <= 500 @@ -398,6 +415,7 @@ public class DayQuestion res.Add(nums[index]); index--; } + return res; } @@ -405,11 +423,8 @@ public class DayQuestion #region day 8.9 - /* 1413. Minimum Value to Get Positive Step by Step Sum - * - * Given an array of integers nums, you start with an initial positive value startValue. - * In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right). - * Return the minimum positive value of startValue such that the step by step sum is never less than 1. + /* + * 1413. Minimum Value to Get Positive Step by Step Sum */ public int MinStartValue(int[] nums) { @@ -419,8 +434,45 @@ public class DayQuestion cur += nums[i]; min = Math.Min(min, cur); } + return -min + 1; } #endregion + + #region day 8.12 + + /* + * 1282. Group the People Given the Group Size They Belong To + * [3,3,3,3,3,1,3] + * [[5],[0,1,2],[3,4,6]] + */ + public IList> GroupThePeople(int[] groupSizes) + { + var groupDic = new Dictionary>(); + for (var i = 0; i < groupSizes.Length; i++) + { + // 先把相同分组的人全塞进去 在分组拿出来 + var groupList = groupDic.GetValueOrDefault(groupSizes[i]) ?? new List(); + groupList.Add(i); + if (!groupDic.TryAdd(groupSizes[i], groupList)) groupDic[groupSizes[i]] = groupList; + } + IList> res = new List>(); + foreach (var k in groupDic.Keys) + { + List getList = groupDic[k], tempRes = new List(); + foreach (var item in getList) + { + tempRes.Add(item); + if (tempRes.Count == k) // 按组分 + { + res.Add(tempRes); + tempRes = new List(); + } + } + } + return res; + } + + #endregion } \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/QueueSection/MyCircularDeque.cs b/cSharp-source/Solution/1-Basic/QueueSection/MyCircularDeque.cs new file mode 100644 index 0000000..217f938 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/QueueSection/MyCircularDeque.cs @@ -0,0 +1,62 @@ +namespace QueueSection; + +public class MyCircularDeque +{ + private int capacity; + private int[] arr; + private int front; + private int rear; + + public MyCircularDeque(int k) + { + capacity = k + 1; + arr = new int[capacity]; + rear = 0; + front = 0; + } + + public bool InsertFront(int value) + { + if (IsFull()) return false; + front = (front - 1 + capacity) % capacity; + arr[front] = value; + return true; + } + + public bool InsertLast(int value) + { + if (IsFull()) return false; + arr[rear] = value; + rear = (rear + 1) % capacity; + return true; + } + + public bool DeleteFront() + { + if (IsEmpty()) return false; + front = (front + 1) % capacity; + return true; + } + + public bool DeleteLast() + { + if (IsEmpty()) return false; + rear = (rear - 1 + capacity) % capacity; + return true; + } + + public int GetFront() + { + if (IsEmpty()) return -1; + return arr[front]; + } + + public int GetRear() + { + if (IsEmpty()) return -1; + return arr[(rear - 1 + capacity) % capacity]; // 防止0作为被除数 + } + + public bool IsEmpty() => front == rear; + public bool IsFull() => (rear + 1) % capacity == front; +} \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs index 0755c1b..1f49e70 100644 --- a/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs @@ -83,6 +83,7 @@ public class DayQuestion return sb.ToString(); } + #endregion #region day 8.10 @@ -135,6 +136,7 @@ public class DayQuestion temp.Append(s[idx]); idx++; } + curNum = Convert.ToInt32(temp.ToString()) * curSign * sign; if (idx < s.Length && s[idx] == 'x') @@ -167,6 +169,7 @@ public class DayQuestion if (s[i] >= 'a') l.Append(s[i]); else d.Append(s[i]); } + int n = d.Length, m = l.Length, end = m + n; if (Math.Abs(n - m) > 1) return ""; @@ -181,8 +184,34 @@ public class DayQuestion else res.Append(l[--m]); } } + return res.ToString(); } #endregion + + #region day 8.14 + + /* + 1422. Maximum Score After Splitting a String + Given a string s of zeros and ones, return the maximum score after + splitting the string into two non-empty substrings (i.e. left substring and right substring). + The score after splitting a string is the number of zeros in the left substring plus + the number of ones in the right substring. + */ + public int MaxScore(string s) + { + int n = s.Length, ans = 0; + var sums = new int[n + 10]; + for (var i = 1; i <= n; i++) sums[i] = sums[i - 1] + (s[i - 1] - '0'); + for (var i = 1; i <= n; i++) + { + var zeros = i - sums[i]; + var ones = sums[n] - sums[i]; + ans = Math.Max(ans, zeros + ones); + } + return ans; + } + + #endregion } \ No newline at end of file diff --git a/go-source/src/1-basic/arraySection/dayQuestion.go b/go-source/src/1-basic/arraySection/dayQuestion.go index e81fd13..a399a1b 100644 --- a/go-source/src/1-basic/arraySection/dayQuestion.go +++ b/go-source/src/1-basic/arraySection/dayQuestion.go @@ -212,3 +212,24 @@ func minSubsequence(nums []int) []int { } return res } + +func groupThePeople(groupSizes []int) [][]int { + groupMap := map[int][]int{} + var res [][]int + for i := 0; i < len(groupSizes); i++ { + groupSlice := groupMap[groupSizes[i]] + groupSlice = append(groupSlice, i) + groupMap[groupSizes[i]] = groupSlice + } + for k, list := range groupMap { + var temp []int + for i := 0; i < len(list); i++ { + temp = append(temp, list[i]) + if k == len(temp) { + res = append(res, temp) + temp = []int{} + } + } + } + return res +} diff --git a/go-source/src/1-basic/stringSection/dayQuestion.go b/go-source/src/1-basic/stringSection/dayQuestion.go index 2324095..fd94d53 100644 --- a/go-source/src/1-basic/stringSection/dayQuestion.go +++ b/go-source/src/1-basic/stringSection/dayQuestion.go @@ -72,3 +72,24 @@ func solveEquation(equation string) string { } return "No solution" } + +/* +1422. Maximum Score After Splitting a String +Given a string s of zeros and ones, return the maximum score after +splitting the string into two non-empty substrings (i.e. left substring and right substring). +The score after splitting a string is the number of zeros in the left substring plus +the number of ones in the right substring. +*/ +func maxScore(s string) int { + n := len(s) + presum, ans := 0, -1-n + for i := 0; i < n; i++ { + if cur := presum*2 - i; i > 0 && cur > ans { + ans = cur + } + if s[i] == '0' { + presum++ + } + } + return ans + n - presum +} diff --git a/go-source/src/main.go b/go-source/src/main.go index 01f9435..3266d2a 100644 --- a/go-source/src/main.go +++ b/go-source/src/main.go @@ -1,24 +1,15 @@ package main -import "fmt" +import ( + "fmt" + "time" +) func main() { - a := []int{1, 2, 3, 4, 5, 6} - b := []int{1, 2, 3, 4, 5, 6} - - fmt.Println("cap a:", cap(a)) - a = append(a[:0], a[1:]...) - fmt.Println("slice a:", a) - - fmt.Println("cap b:", cap(b)) - b = append(b[:1+copy(b[:1], b[:2])]) - fmt.Println("cap b after reduce:", cap(b)) - fmt.Println("slice b:", b) - -} - -func inc() (v int) { - v = 13 - defer func() { v++ }() - return 42 + now := time.Now() + fmt.Println(now) + fmt.Printf("%4d.%02d.%02d\n", now.Year(), now.Month(), now.Day()) + fmt.Println(now.Format(time.RFC822)) + fmt.Println(now.Format(time.ANSIC)) + fmt.Println(now.Format("02 Jan 2006 15:04")) } -- Gitee From 47944502cccb9110575fde654e86b0218c9cf343 Mon Sep 17 00:00:00 2001 From: zhousl Date: Tue, 16 Aug 2022 19:19:34 +0800 Subject: [PATCH 24/31] =?UTF-8?q?[#update]=20=E6=B2=A1=E5=86=99=E5=AE=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../OrderSetSection/OrderedStream.cs | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 cSharp-source/Solution/2-External/OrderSetSection/OrderedStream.cs diff --git a/cSharp-source/Solution/2-External/OrderSetSection/OrderedStream.cs b/cSharp-source/Solution/2-External/OrderSetSection/OrderedStream.cs new file mode 100644 index 0000000..23e004c --- /dev/null +++ b/cSharp-source/Solution/2-External/OrderSetSection/OrderedStream.cs @@ -0,0 +1,26 @@ +namespace OrderSetSection; + +public class OrderedStream +{ + /* + 1656. Design an Ordered Stream + There is a stream of n (idKey, value) pairs arriving in an arbitrary order, + where idKey is an integer between 1 and n and value is a string. No two pairs have the same id. + Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. + The concatenation of all the chunks should result in a list of the sorted values. + + OrderedStream(int n) Constructs the stream to take n values. + String[] insert(int idKey, String value) Inserts the pair (idKey, value) into the stream, + then returns the largest possible chunk of currently inserted values that appear next in the order. + */ + + public OrderedStream(int n) + { + + } + + public IList Insert(int idKey, string value) + { + return null; + } +} -- Gitee From 6a673d68e2f0e9d2d3d925119dea7878e3bdca12 Mon Sep 17 00:00:00 2001 From: zhousl Date: Tue, 16 Aug 2022 19:47:01 +0800 Subject: [PATCH 25/31] [#update] --- .../OrderSetSection/OrderedStream.cs | 30 ++++++++++++------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/cSharp-source/Solution/2-External/OrderSetSection/OrderedStream.cs b/cSharp-source/Solution/2-External/OrderSetSection/OrderedStream.cs index 23e004c..a0c7324 100644 --- a/cSharp-source/Solution/2-External/OrderSetSection/OrderedStream.cs +++ b/cSharp-source/Solution/2-External/OrderSetSection/OrderedStream.cs @@ -3,24 +3,32 @@ public class OrderedStream { /* - 1656. Design an Ordered Stream - There is a stream of n (idKey, value) pairs arriving in an arbitrary order, - where idKey is an integer between 1 and n and value is a string. No two pairs have the same id. - Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. - The concatenation of all the chunks should result in a list of the sorted values. - - OrderedStream(int n) Constructs the stream to take n values. - String[] insert(int idKey, String value) Inserts the pair (idKey, value) into the stream, - then returns the largest possible chunk of currently inserted values that appear next in the order. + 1656. Design an Ordered Stream + There is a stream of n (idKey, value) pairs arriving in an arbitrary order, + where idKey is an integer between 1 and n and value is a string. No two pairs have the same id. + Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. + The concatenation of all the chunks should result in a list of the sorted values. + + OrderedStream(int n) Constructs the stream to take n values. + String[] insert(int idKey, String value) Inserts the pair (idKey, value) into the stream, + then returns the largest possible chunk of currently inserted values that appear next in the order. */ + private string[] arr; + private int _ptr; + public OrderedStream(int n) { - + arr = new string[n + 2]; + Array.Fill(arr, ""); + _ptr = 1; } public IList Insert(int idKey, string value) { - return null; + IList ans = new List(); + arr[idKey] = value; + while (arr[_ptr].Length == 5) ans.Add(arr[_ptr++]); + return ans; } } -- Gitee From 2eda1caec3921cfedfbe2891b731c1922208ada2 Mon Sep 17 00:00:00 2001 From: zhousl Date: Sat, 20 Aug 2022 23:52:44 +0800 Subject: [PATCH 26/31] =?UTF-8?q?[#add]=20=E6=AF=8F=E6=97=A5=E4=B8=80?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1-Basic/TreeSection/DayQuestion.cs | 51 +++++++++++++++++-- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs index 39a82ba..cfdc67d 100644 --- a/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs @@ -1,4 +1,6 @@ -namespace TreeSection; +#pragma warning disable CS8625 +namespace TreeSection; + public class DayQuestion { #region day 6.24 @@ -29,13 +31,16 @@ public class DayQuestion if (node.left != null) treeQueue.Enqueue(node.left); if (node.right != null) treeQueue.Enqueue(node.right); } + res.Add(max); } + return res; } int _max = 0; - Dictionary dic = new Dictionary(); + private readonly Dictionary dic = new Dictionary(); + public IList LargestValuesDFS(TreeNode root) { IList res = new List(); @@ -95,9 +100,11 @@ public class DayQuestion if (cur.left != null) queue.Enqueue(cur.left); if (cur.right != null) queue.Enqueue(cur.right); } + if (sum > num) (res, num) = (level, sum); level++; } + return res; } @@ -137,6 +144,7 @@ public class DayQuestion if (node.left != null) temp.Enqueue(node.left); if (node.right != null) temp.Enqueue(node.right); } + queue = temp; curDepth++; } @@ -147,8 +155,45 @@ public class DayQuestion depthNode.left = new TreeNode(val, depthNode.left, null); depthNode.right = new TreeNode(val, null, depthNode.right); } + + return root; + } + + #endregion + + #region day 8.20 + + /* + 654. Maximum Binary Tree + */ + public TreeNode ConstructMaximumBinaryTree(int[] nums) + { + return MyBuild(nums, 0, nums.Length - 1); + } + + private TreeNode MyBuild(int[] nums, int left, int right) + { + if (left > right) + return null; + + int max = int.MinValue; + int index = 0; + for (int i = left; i <= right; i++) + { + if (max < nums[i]) + { + max = nums[i]; + index = i; + } + } + + var root = new TreeNode(max) + { + left = MyBuild(nums, left, index - 1), + right = MyBuild(nums, index + 1, right) + }; return root; } #endregion -} +} \ No newline at end of file -- Gitee From 784e7dd0bb5647996f7385e4f8ee51f45d3e6f54 Mon Sep 17 00:00:00 2001 From: zhousl Date: Sun, 4 Sep 2022 12:20:56 +0800 Subject: [PATCH 27/31] [#update] --- .../1-Basic/ArraySection/ArraySection.csproj | 1 - .../1-Basic/ArraySection/DayQuestion.cs | 31 +++ .../Solution/1-Basic/ArraySection/Program.cs | 1 - .../1-Basic/LinkSection/LinkSection.csproj | 1 - .../Solution/1-Basic/LinkSection/Program.cs | 1 - .../Solution/1-Basic/QueueSection/Program.cs | 1 - .../1-Basic/QueueSection/QueueSection.csproj | 1 - .../Solution/1-Basic/StackSection/Program.cs | 9 - .../1-Basic/StackSection/StackSection.csproj | 1 - .../1-Basic/StringSection/DayQuestion.cs | 16 ++ .../Solution/1-Basic/StringSection/Program.cs | 1 - .../StringSection/StringSection.csproj | 1 - .../1-Basic/TreeSection/DayQuestion.cs | 237 ++++++++++++------ .../Solution/1-Basic/TreeSection/Program.cs | 1 - .../1-Basic/TreeSection/TreeSection.csproj | 1 - .../2-External/DPSection/DPSection.csproj | 1 - .../2-External/DPSection/DayQuestion.cs | 33 ++- .../Solution/2-External/DPSection/Program.cs | 1 - .../2-External/MathSection/MathSection.csproj | 1 - .../2-External/MathSection/Program.cs | 1 - .../OrderSetSection/OrderSetSection.csproj | 1 - .../2-External/OrderSetSection/Program.cs | 1 - .../2-External/TrieSection/Program.cs | 1 - .../2-External/TrieSection/TrieSection.csproj | 1 - .../Solution/3-Bucket/HOT100/Cluster.cs | 75 ++++++ .../Solution/3-Bucket/HOT100/ListNode.cs | 13 + cSharp-source/Solution/Solution.sln | 9 + .../src/1-basic/arraySection/dayQuestion.go | 12 +- .../src/1-basic/linkSection/removeLink.go | 18 ++ 29 files changed, 362 insertions(+), 110 deletions(-) delete mode 100644 cSharp-source/Solution/1-Basic/ArraySection/Program.cs delete mode 100644 cSharp-source/Solution/1-Basic/LinkSection/Program.cs delete mode 100644 cSharp-source/Solution/1-Basic/QueueSection/Program.cs delete mode 100644 cSharp-source/Solution/1-Basic/StackSection/Program.cs delete mode 100644 cSharp-source/Solution/1-Basic/StringSection/Program.cs delete mode 100644 cSharp-source/Solution/1-Basic/TreeSection/Program.cs delete mode 100644 cSharp-source/Solution/2-External/DPSection/Program.cs delete mode 100644 cSharp-source/Solution/2-External/MathSection/Program.cs delete mode 100644 cSharp-source/Solution/2-External/OrderSetSection/Program.cs delete mode 100644 cSharp-source/Solution/2-External/TrieSection/Program.cs create mode 100644 cSharp-source/Solution/3-Bucket/HOT100/Cluster.cs create mode 100644 cSharp-source/Solution/3-Bucket/HOT100/ListNode.cs diff --git a/cSharp-source/Solution/1-Basic/ArraySection/ArraySection.csproj b/cSharp-source/Solution/1-Basic/ArraySection/ArraySection.csproj index b9de063..eb2460e 100644 --- a/cSharp-source/Solution/1-Basic/ArraySection/ArraySection.csproj +++ b/cSharp-source/Solution/1-Basic/ArraySection/ArraySection.csproj @@ -1,7 +1,6 @@ - Exe net6.0 enable enable diff --git a/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs index d9cc21e..37b7f71 100644 --- a/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs @@ -457,6 +457,7 @@ public class DayQuestion groupList.Add(i); if (!groupDic.TryAdd(groupSizes[i], groupList)) groupDic[groupSizes[i]] = groupList; } + IList> res = new List>(); foreach (var k in groupDic.Keys) { @@ -471,6 +472,36 @@ public class DayQuestion } } } + + return res; + } + + #endregion + + #region day 9.4 + + public int NumSpecial(int[][] mat) + { + int res = 0; + var rows = new int[mat.Length]; + var cols = new int[mat[0].Length]; + for (int i = 0; i < mat.Length; i++) + { + for (int j = 0; j < mat[0].Length; j++) + { + rows[i] += mat[i][j]; + cols[j] += mat[i][j]; + } + } + + for (int i = 0; i < mat.Length; i++) + { + for (int j = 0; j < mat[0].Length; j++) + { + if (mat[i][j] == 1 && rows[i] == 1 && cols[j] == 1) res += 1; + } + } + return res; } diff --git a/cSharp-source/Solution/1-Basic/ArraySection/Program.cs b/cSharp-source/Solution/1-Basic/ArraySection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/1-Basic/ArraySection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/LinkSection/LinkSection.csproj b/cSharp-source/Solution/1-Basic/LinkSection/LinkSection.csproj index 2c6cde9..9bd7357 100644 --- a/cSharp-source/Solution/1-Basic/LinkSection/LinkSection.csproj +++ b/cSharp-source/Solution/1-Basic/LinkSection/LinkSection.csproj @@ -1,7 +1,6 @@ - Exe net6.0 enable enable diff --git a/cSharp-source/Solution/1-Basic/LinkSection/Program.cs b/cSharp-source/Solution/1-Basic/LinkSection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/1-Basic/LinkSection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/QueueSection/Program.cs b/cSharp-source/Solution/1-Basic/QueueSection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/1-Basic/QueueSection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/QueueSection/QueueSection.csproj b/cSharp-source/Solution/1-Basic/QueueSection/QueueSection.csproj index b9de063..eb2460e 100644 --- a/cSharp-source/Solution/1-Basic/QueueSection/QueueSection.csproj +++ b/cSharp-source/Solution/1-Basic/QueueSection/QueueSection.csproj @@ -1,7 +1,6 @@ - Exe net6.0 enable enable diff --git a/cSharp-source/Solution/1-Basic/StackSection/Program.cs b/cSharp-source/Solution/1-Basic/StackSection/Program.cs deleted file mode 100644 index be38953..0000000 --- a/cSharp-source/Solution/1-Basic/StackSection/Program.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace StackSection; - -internal class Program -{ - static void Main(string[] args) - { - Console.WriteLine("Hello, World!"); - } -} diff --git a/cSharp-source/Solution/1-Basic/StackSection/StackSection.csproj b/cSharp-source/Solution/1-Basic/StackSection/StackSection.csproj index 74abf5c..132c02c 100644 --- a/cSharp-source/Solution/1-Basic/StackSection/StackSection.csproj +++ b/cSharp-source/Solution/1-Basic/StackSection/StackSection.csproj @@ -1,7 +1,6 @@ - Exe net6.0 enable enable diff --git a/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs index 1f49e70..85b0834 100644 --- a/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs @@ -210,8 +210,24 @@ public class DayQuestion var ones = sums[n] - sums[i]; ans = Math.Max(ans, zeros + ones); } + return ans; } #endregion + + #region day 8.21 + + public int IsPrefixOfWord(string sentence, string searchWord) + { + var splits = sentence.Split(' '); + for (var i = 0; i < splits.Length; i++) + { + if (splits[i].StartsWith(searchWord)) return i + 1; + } + + return -1; + } + + #endregion } \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/StringSection/Program.cs b/cSharp-source/Solution/1-Basic/StringSection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/1-Basic/StringSection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/StringSection/StringSection.csproj b/cSharp-source/Solution/1-Basic/StringSection/StringSection.csproj index b9de063..eb2460e 100644 --- a/cSharp-source/Solution/1-Basic/StringSection/StringSection.csproj +++ b/cSharp-source/Solution/1-Basic/StringSection/StringSection.csproj @@ -1,7 +1,6 @@ - Exe net6.0 enable enable diff --git a/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs index cfdc67d..878f92d 100644 --- a/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs @@ -3,77 +3,23 @@ namespace TreeSection; public class DayQuestion { - #region day 6.24 - - //515. Find Largest Value in Each Tree Row - // Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed) - - //Input: root = [1,3,2,5,3,null,9] - //Output: [1,3,9] - - //Input: root = [1,2,3] - //Output: [1,3] - - public IList LargestValuesBFS(TreeNode root) - { - IList res = new List(); - if (root == null) return res; - - var treeQueue = new Queue(); - treeQueue.Enqueue(root); - while (treeQueue.Any()) - { - int size = treeQueue.Count, max = treeQueue.Peek().val; - while (size-- > 0) - { - var node = treeQueue.Dequeue(); - max = Math.Max(max, node.val); - if (node.left != null) treeQueue.Enqueue(node.left); - if (node.right != null) treeQueue.Enqueue(node.right); - } - - res.Add(max); - } - - return res; - } - - int _max = 0; - private readonly Dictionary dic = new Dictionary(); - - public IList LargestValuesDFS(TreeNode root) - { - IList res = new List(); - DFS(root, 1); - for (int i = 1; i <= _max; i++) res.Add(dic[i]); - return res; - } - - private void DFS(TreeNode root, int depth) - { - if (root == null) return; - _max = Math.Max(_max, depth); - - if (dic.ContainsKey(depth)) - dic[depth] = Math.Max(dic[depth], root.val); - else - dic.Add(depth, root.val); - - DFS(root.left, depth + 1); - DFS(root.right, depth + 1); - } - - #endregion - #region day 7.21 //814. Binary Tree Pruning public TreeNode PruneTree(TreeNode root) { - if (root == null) return null; + if (root == null) + { + return null; + } + root.left = PruneTree(root.left); root.right = PruneTree(root.right); - if (root.left == null && root.right == null && root.val == 0) root = null; + if (root.left == null && root.right == null && root.val == 0) + { + root = null; + } + return root; } @@ -97,11 +43,22 @@ public class DayQuestion { var cur = queue.Dequeue(); sum += cur.val; - if (cur.left != null) queue.Enqueue(cur.left); - if (cur.right != null) queue.Enqueue(cur.right); + if (cur.left != null) + { + queue.Enqueue(cur.left); + } + + if (cur.right != null) + { + queue.Enqueue(cur.right); + } + } + + if (sum > num) + { + (res, num) = (level, sum); } - if (sum > num) (res, num) = (level, sum); level++; } @@ -131,18 +88,25 @@ public class DayQuestion return tree; } - Queue queue = new Queue(); + var queue = new Queue(); queue.Enqueue(root); - int curDepth = 1; + var curDepth = 1; while (curDepth < depth - 1) { var temp = new Queue(); while (queue.Any()) { var node = queue.Dequeue(); - if (node.left != null) temp.Enqueue(node.left); - if (node.right != null) temp.Enqueue(node.right); + if (node.left != null) + { + temp.Enqueue(node.left); + } + + if (node.right != null) + { + temp.Enqueue(node.right); + } } queue = temp; @@ -161,6 +125,90 @@ public class DayQuestion #endregion + #region day 6.24 + + //515. Find Largest Value in Each Tree Row + // Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed) + + //Input: root = [1,3,2,5,3,null,9] + //Output: [1,3,9] + + //Input: root = [1,2,3] + //Output: [1,3] + + public IList LargestValuesBFS(TreeNode root) + { + IList res = new List(); + if (root == null) + { + return res; + } + + var treeQueue = new Queue(); + treeQueue.Enqueue(root); + while (treeQueue.Any()) + { + int size = treeQueue.Count, max = treeQueue.Peek().val; + while (size-- > 0) + { + var node = treeQueue.Dequeue(); + max = Math.Max(max, node.val); + if (node.left != null) + { + treeQueue.Enqueue(node.left); + } + + if (node.right != null) + { + treeQueue.Enqueue(node.right); + } + } + + res.Add(max); + } + + return res; + } + + private int _max = 0; + private readonly Dictionary dic = new(); + + public IList LargestValuesDFS(TreeNode root) + { + IList res = new List(); + DFS(root, 1); + for (var i = 1; i <= _max; i++) + { + res.Add(dic[i]); + } + + return res; + } + + private void DFS(TreeNode root, int depth) + { + if (root == null) + { + return; + } + + _max = Math.Max(_max, depth); + + if (dic.ContainsKey(depth)) + { + dic[depth] = Math.Max(dic[depth], root.val); + } + else + { + dic.Add(depth, root.val); + } + + DFS(root.left, depth + 1); + DFS(root.right, depth + 1); + } + + #endregion + #region day 8.20 /* @@ -170,15 +218,17 @@ public class DayQuestion { return MyBuild(nums, 0, nums.Length - 1); } - + private TreeNode MyBuild(int[] nums, int left, int right) { if (left > right) + { return null; + } - int max = int.MinValue; - int index = 0; - for (int i = left; i <= right; i++) + var max = int.MinValue; + var index = 0; + for (var i = left; i <= right; i++) { if (max < nums[i]) { @@ -196,4 +246,41 @@ public class DayQuestion } #endregion + + #region day 8.22 + + //655. Print Binary Tree + public IList> PrintTree(TreeNode root) + { + IList> result = new List>(); + var d = 0; + d = Depth(root); + var width = (int)Math.Pow(2, d); + for (var i = 0; i < d; i++) + { + IList list = new List(); + for (var j = 0; j < width - 1; j++) + list.Add(""); + result.Add(list); + } + + Fill(result, root, 0, width - 1, 0); + return result; + } + + private int Depth(TreeNode node) + { + return node == null ? 0 : Math.Max(Depth(node.left) + 1, Depth(node.right) + 1); + } + + private void Fill(IList> result, TreeNode root, int l, int r, int depth) + { + if (root == null) return; + + result[depth][(l + r) / 2] = Convert.ToString(root.val); + Fill(result, root.left, l, (l + r) / 2, depth + 1); + Fill(result, root.right, (l + r) / 2 + 1, r, depth + 1); + } + + #endregion } \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/TreeSection/Program.cs b/cSharp-source/Solution/1-Basic/TreeSection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/1-Basic/TreeSection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/1-Basic/TreeSection/TreeSection.csproj b/cSharp-source/Solution/1-Basic/TreeSection/TreeSection.csproj index d33f8bd..70877dd 100644 --- a/cSharp-source/Solution/1-Basic/TreeSection/TreeSection.csproj +++ b/cSharp-source/Solution/1-Basic/TreeSection/TreeSection.csproj @@ -1,7 +1,6 @@ - Exe net6.0 enable enable diff --git a/cSharp-source/Solution/2-External/DPSection/DPSection.csproj b/cSharp-source/Solution/2-External/DPSection/DPSection.csproj index 74abf5c..132c02c 100644 --- a/cSharp-source/Solution/2-External/DPSection/DPSection.csproj +++ b/cSharp-source/Solution/2-External/DPSection/DPSection.csproj @@ -1,7 +1,6 @@ - Exe net6.0 enable enable diff --git a/cSharp-source/Solution/2-External/DPSection/DayQuestion.cs b/cSharp-source/Solution/2-External/DPSection/DayQuestion.cs index 6d11dbd..7fd8046 100644 --- a/cSharp-source/Solution/2-External/DPSection/DayQuestion.cs +++ b/cSharp-source/Solution/2-External/DPSection/DayQuestion.cs @@ -28,8 +28,11 @@ public class DayQuestion int d = Math.Min(b, c) + costs[i][0]; int e = Math.Min(a, c) + costs[i][1]; int f = Math.Min(a, b) + costs[i][2]; - a = d; b = e; c = f; + a = d; + b = e; + c = f; } + return Math.Min(a, Math.Min(b, c)); } @@ -64,8 +67,10 @@ public class DayQuestion if (i == j) continue; if (Check(strs[i], strs[j])) notSame = false; } + if (notSame) res = strs[i].Length; } + return res; } @@ -91,8 +96,32 @@ public class DayQuestion if (f[i][j] == n) return true; } } + return false; } #endregion -} + + #region day 9.3 + + public int FindLongestChain(int[][] pairs) + { + Array.Sort(pairs, (a, b) => a[0] - b[0]); + int lens = pairs.Length, ans = 1; + int[] f = new int[lens]; + for (int i = 0; i < lens; i++) + { + f[i] = 1; + for (int j = i - 1; j >= 0 && f[i] == 1; j--) + { + if (pairs[j][1] < pairs[i][0]) f[i] = f[j] + 1; + } + + ans = Math.Max(ans, f[i]); + } + + return ans; + } + + #endregion +} \ No newline at end of file diff --git a/cSharp-source/Solution/2-External/DPSection/Program.cs b/cSharp-source/Solution/2-External/DPSection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/2-External/DPSection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/2-External/MathSection/MathSection.csproj b/cSharp-source/Solution/2-External/MathSection/MathSection.csproj index 74abf5c..132c02c 100644 --- a/cSharp-source/Solution/2-External/MathSection/MathSection.csproj +++ b/cSharp-source/Solution/2-External/MathSection/MathSection.csproj @@ -1,7 +1,6 @@ - Exe net6.0 enable enable diff --git a/cSharp-source/Solution/2-External/MathSection/Program.cs b/cSharp-source/Solution/2-External/MathSection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/2-External/MathSection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/2-External/OrderSetSection/OrderSetSection.csproj b/cSharp-source/Solution/2-External/OrderSetSection/OrderSetSection.csproj index 74abf5c..132c02c 100644 --- a/cSharp-source/Solution/2-External/OrderSetSection/OrderSetSection.csproj +++ b/cSharp-source/Solution/2-External/OrderSetSection/OrderSetSection.csproj @@ -1,7 +1,6 @@ - Exe net6.0 enable enable diff --git a/cSharp-source/Solution/2-External/OrderSetSection/Program.cs b/cSharp-source/Solution/2-External/OrderSetSection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/2-External/OrderSetSection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/2-External/TrieSection/Program.cs b/cSharp-source/Solution/2-External/TrieSection/Program.cs deleted file mode 100644 index 837131c..0000000 --- a/cSharp-source/Solution/2-External/TrieSection/Program.cs +++ /dev/null @@ -1 +0,0 @@ -Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/cSharp-source/Solution/2-External/TrieSection/TrieSection.csproj b/cSharp-source/Solution/2-External/TrieSection/TrieSection.csproj index b9de063..eb2460e 100644 --- a/cSharp-source/Solution/2-External/TrieSection/TrieSection.csproj +++ b/cSharp-source/Solution/2-External/TrieSection/TrieSection.csproj @@ -1,7 +1,6 @@ - Exe net6.0 enable enable diff --git a/cSharp-source/Solution/3-Bucket/HOT100/Cluster.cs b/cSharp-source/Solution/3-Bucket/HOT100/Cluster.cs new file mode 100644 index 0000000..f721f3c --- /dev/null +++ b/cSharp-source/Solution/3-Bucket/HOT100/Cluster.cs @@ -0,0 +1,75 @@ +namespace HOT100; + +public class Cluster +{ + // 1.TwoSum + public int[] TwoSum(int[] nums, int target) + { + int[] res = new int[2]; + if (nums == null || nums.Length == 0) return res; + Dictionary dic = new Dictionary(); + + for (int i = 0; i < nums.Length; i++) + { + int temp = target - nums[i]; + if (dic.ContainsKey(temp)) + { + res[0] = dic[temp]; + res[1] = i; + } + + dic.TryAdd(nums[i], i); + } + + return res; + } + + // 2.Add Two Numbers + public ListNode AddTwoNumbers(ListNode l1, ListNode l2) + { + ListNode dummy = new ListNode(-1); + ListNode pre = dummy; + int temp = 0; + + while (l1 != null || l2 != null || temp != 0) + { + if (l1 != null) + { + temp += l1.val; + l1 = l1.next; + } + + if (l2 != null) + { + temp += l2.val; + l2 = l2.next; + } + + pre.next = new ListNode(temp % 10); + pre = pre.next; + temp = temp / 10; + } + + return dummy.next; + } + + // 3. Longest Substring Without Repeating Characters + public int LengthOfLongestSubstring(string s) + { + Queue slide = new Queue(); + int ans = 0; + for (int i = 0; i < s.Length; i++) + { + if (!slide.Contains(s[i])) slide.Enqueue(s[i]); + else + { + while (slide.Contains(s[i])) slide.Dequeue(); + slide.Enqueue(s[i]); + } + + ans = Math.Max(ans, slide.Count); + } + + return ans; + } +} \ No newline at end of file diff --git a/cSharp-source/Solution/3-Bucket/HOT100/ListNode.cs b/cSharp-source/Solution/3-Bucket/HOT100/ListNode.cs new file mode 100644 index 0000000..1071002 --- /dev/null +++ b/cSharp-source/Solution/3-Bucket/HOT100/ListNode.cs @@ -0,0 +1,13 @@ +namespace HOT100; + +public class ListNode +{ + public int val; + public ListNode next; + + public ListNode(int val = 0, ListNode next = null) + { + this.val = val; + this.next = next; + } +} \ No newline at end of file diff --git a/cSharp-source/Solution/Solution.sln b/cSharp-source/Solution/Solution.sln index 6e3bd36..546c807 100644 --- a/cSharp-source/Solution/Solution.sln +++ b/cSharp-source/Solution/Solution.sln @@ -38,6 +38,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TrieSection", "2-External\T EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MathSection", "2-External\MathSection\MathSection.csproj", "{966165B5-25B4-406E-A2F4-5F1B87E0F0BE}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HOT100", "3-Bucket\HOT100\HOT100.csproj", "{E1915DCB-4C68-4C21-BE9C-C48FD96E317A}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "3-Bucket", "3-Bucket", "{A93CFA6A-A24F-4A88-A7C1-D456A8C3A204}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -92,6 +96,10 @@ Global {966165B5-25B4-406E-A2F4-5F1B87E0F0BE}.Debug|Any CPU.Build.0 = Debug|Any CPU {966165B5-25B4-406E-A2F4-5F1B87E0F0BE}.Release|Any CPU.ActiveCfg = Release|Any CPU {966165B5-25B4-406E-A2F4-5F1B87E0F0BE}.Release|Any CPU.Build.0 = Release|Any CPU + {E1915DCB-4C68-4C21-BE9C-C48FD96E317A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E1915DCB-4C68-4C21-BE9C-C48FD96E317A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E1915DCB-4C68-4C21-BE9C-C48FD96E317A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E1915DCB-4C68-4C21-BE9C-C48FD96E317A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -109,6 +117,7 @@ Global {35FD5694-B1B8-4FD5-8FA8-896243F99EAB} = {5D2E938C-2618-4DD9-A439-F193655266A0} {95F18BB5-F085-4CE2-86DC-2322CFF768A2} = {5D2E938C-2618-4DD9-A439-F193655266A0} {966165B5-25B4-406E-A2F4-5F1B87E0F0BE} = {5D2E938C-2618-4DD9-A439-F193655266A0} + {E1915DCB-4C68-4C21-BE9C-C48FD96E317A} = {A93CFA6A-A24F-4A88-A7C1-D456A8C3A204} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B95AEA45-E93F-42C8-990A-4C410797B0C6} diff --git a/go-source/src/1-basic/arraySection/dayQuestion.go b/go-source/src/1-basic/arraySection/dayQuestion.go index a399a1b..0cae9c1 100644 --- a/go-source/src/1-basic/arraySection/dayQuestion.go +++ b/go-source/src/1-basic/arraySection/dayQuestion.go @@ -7,11 +7,13 @@ import ( /* Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. - A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: - 0 <= i, j < nums.length - i != j - nums[i] - nums[j] == k - Notice that |val| denotes the absolute value of val. + + A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: + 0 <= i, j < nums.length + i != j + nums[i] - nums[j] == k + Notice that |val| denotes the absolute value of val. + Example 1: Input: nums = [3,1,4,1,5], k = 2 Output: 2 diff --git a/go-source/src/1-basic/linkSection/removeLink.go b/go-source/src/1-basic/linkSection/removeLink.go index 66805f3..c48f0dd 100644 --- a/go-source/src/1-basic/linkSection/removeLink.go +++ b/go-source/src/1-basic/linkSection/removeLink.go @@ -22,3 +22,21 @@ func removeElements(head *ListNode, val int) *ListNode { } return dummyHead.Next } + +func removeNthFromEnd(head *ListNode, n int) *ListNode { + dummyHead := &ListNode{} + dummyHead.Next = head + slow := dummyHead + fast := dummyHead + + for i := 0; i < n && fast != nil; i++ { + fast = fast.Next + } + fast = fast.Next + for fast != nil { + fast = fast.Next + slow = slow.Next + } + slow.Next = slow.Next.Next + return dummyHead.Next +} -- Gitee From 3d2fdff1b5e23ffdaf16e3afde30d93012bf168a Mon Sep 17 00:00:00 2001 From: zhousl Date: Mon, 10 Oct 2022 11:00:20 +0800 Subject: [PATCH 28/31] [#add] --- .../1-Basic/ArraySection/DayQuestion.cs | 68 +++++++++++++++++++ .../src/1-basic/treeSection/dayQuestion.go | 22 ++++++ 2 files changed, 90 insertions(+) diff --git a/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs index 37b7f71..4a5df35 100644 --- a/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs +++ b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs @@ -506,4 +506,72 @@ public class DayQuestion } #endregion + + #region day 8.18 + + /* + 1224. Maximum Equal Frequency + Given an array nums of positive integers, return the longest possible length of an array prefix of nums, + such that it is possible to remove exactly one element from this prefix so that every number + that has appeared in it will have the same number of occurrences. + If after removing one element there are no remaining elements, + it's still considered that every appeared number has the same number of occurrences (0). + */ + public int MaxEqualFreq(int[] nums) { + int[] count = new int[100010]; + SortedDictionary frequency = new SortedDictionary(); + + int result = 0, length = 0; + foreach (int num in nums){ + if (count[num] > 0){ + frequency[count[num]]--; + if (frequency[count[num]] == 0) frequency.Remove(count[num]); + } + + count[num]++; + if (!frequency.ContainsKey(count[num])) frequency.Add(count[num], 0); + frequency[count[num]]++; + + length++; + + if (frequency.Count == 1){ + foreach (var kv in frequency){ + if (kv.Key == 1 || kv.Value == 1) result = length; + } + } + else if (frequency.Count == 2){ + List freq = new List(); + foreach (var kv in frequency){ + freq.Add(new int[2] {kv.Key, kv.Value}); + } + + if ((freq[0][0] == 1 && freq[0][1] == 1) || (freq[1][0] == 1 && freq[1][1] == 1)) result = length; + else if (freq[1][1] == 1 && Math.Abs(freq[0][0] - freq[1][0]) == 1) result = length; + } + } + + return result; + } + + #endregion + + #region day 8.19 + /* + 1450. Number of Students Doing Homework at a Given Time + Given two integer arrays startTime and endTime and given an integer queryTime. + The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i]. + Return the number of students doing their homework at time queryTime. More formally, + return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive. + */ + public int BusyStudent(int[] startTime, int[] endTime, int queryTime) + { + int len = startTime.Length, ans = 0; + for (int i = 0; i < len; i++) + { + if (queryTime >= startTime[i] && queryTime <= endTime[i]) ans++; + } + return ans; + } + + #endregion } \ No newline at end of file diff --git a/go-source/src/1-basic/treeSection/dayQuestion.go b/go-source/src/1-basic/treeSection/dayQuestion.go index ad55747..e3eaf3c 100644 --- a/go-source/src/1-basic/treeSection/dayQuestion.go +++ b/go-source/src/1-basic/treeSection/dayQuestion.go @@ -58,6 +58,28 @@ func maxLevelSum(root *TreeNode) int { return ans } +//1302. Deepest Leaves Sum +func deepestLeavesSum(root *TreeNode) int { + ans := 0 + queue := []*TreeNode{root} + for size := len(queue); size > 0; size = len(queue) { + cur := 0 + for i := 0; i < size; i++ { + node := queue[0] + queue = queue[1:] + cur += node.Val + if node.Left != nil { + queue = append(queue, node.Left) + } + if node.Right != nil { + queue = append(queue, node.Right) + } + } + ans = cur + } + return ans +} + func max(a, b int) int { if a > b { return a -- Gitee From f93d9974d738712379bb32141e14175de2d1118f Mon Sep 17 00:00:00 2001 From: zhousl Date: Mon, 10 Oct 2022 11:07:22 +0800 Subject: [PATCH 29/31] =?UTF-8?q?[#update]=20=E9=A1=B9=E7=9B=AE=E7=BB=93?= =?UTF-8?q?=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cSharp-source/Solution/3-Bucket/HOT100/ListNode.cs | 1 + cSharp-source/Solution/Solution.sln | 14 +++++++------- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/cSharp-source/Solution/3-Bucket/HOT100/ListNode.cs b/cSharp-source/Solution/3-Bucket/HOT100/ListNode.cs index 1071002..8715956 100644 --- a/cSharp-source/Solution/3-Bucket/HOT100/ListNode.cs +++ b/cSharp-source/Solution/3-Bucket/HOT100/ListNode.cs @@ -1,3 +1,4 @@ +#pragma warning disable CS8625 namespace HOT100; public class ListNode diff --git a/cSharp-source/Solution/Solution.sln b/cSharp-source/Solution/Solution.sln index 546c807..6209d91 100644 --- a/cSharp-source/Solution/Solution.sln +++ b/cSharp-source/Solution/Solution.sln @@ -38,10 +38,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TrieSection", "2-External\T EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MathSection", "2-External\MathSection\MathSection.csproj", "{966165B5-25B4-406E-A2F4-5F1B87E0F0BE}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HOT100", "3-Bucket\HOT100\HOT100.csproj", "{E1915DCB-4C68-4C21-BE9C-C48FD96E317A}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "3-Bucket", "3-Bucket", "{A93CFA6A-A24F-4A88-A7C1-D456A8C3A204}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HOT100", "3-Bucket\HOT100\HOT100.csproj", "{862F0319-D690-43CF-B011-952A64D08E41}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -96,10 +96,10 @@ Global {966165B5-25B4-406E-A2F4-5F1B87E0F0BE}.Debug|Any CPU.Build.0 = Debug|Any CPU {966165B5-25B4-406E-A2F4-5F1B87E0F0BE}.Release|Any CPU.ActiveCfg = Release|Any CPU {966165B5-25B4-406E-A2F4-5F1B87E0F0BE}.Release|Any CPU.Build.0 = Release|Any CPU - {E1915DCB-4C68-4C21-BE9C-C48FD96E317A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E1915DCB-4C68-4C21-BE9C-C48FD96E317A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E1915DCB-4C68-4C21-BE9C-C48FD96E317A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E1915DCB-4C68-4C21-BE9C-C48FD96E317A}.Release|Any CPU.Build.0 = Release|Any CPU + {862F0319-D690-43CF-B011-952A64D08E41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {862F0319-D690-43CF-B011-952A64D08E41}.Debug|Any CPU.Build.0 = Debug|Any CPU + {862F0319-D690-43CF-B011-952A64D08E41}.Release|Any CPU.ActiveCfg = Release|Any CPU + {862F0319-D690-43CF-B011-952A64D08E41}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -117,7 +117,7 @@ Global {35FD5694-B1B8-4FD5-8FA8-896243F99EAB} = {5D2E938C-2618-4DD9-A439-F193655266A0} {95F18BB5-F085-4CE2-86DC-2322CFF768A2} = {5D2E938C-2618-4DD9-A439-F193655266A0} {966165B5-25B4-406E-A2F4-5F1B87E0F0BE} = {5D2E938C-2618-4DD9-A439-F193655266A0} - {E1915DCB-4C68-4C21-BE9C-C48FD96E317A} = {A93CFA6A-A24F-4A88-A7C1-D456A8C3A204} + {862F0319-D690-43CF-B011-952A64D08E41} = {A93CFA6A-A24F-4A88-A7C1-D456A8C3A204} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B95AEA45-E93F-42C8-990A-4C410797B0C6} -- Gitee From 6166e59ecaa956466fa6c83ace6ed171cad32705 Mon Sep 17 00:00:00 2001 From: zhousl Date: Mon, 10 Oct 2022 11:07:49 +0800 Subject: [PATCH 30/31] [#update] --- cSharp-source/Solution/3-Bucket/HOT100/HOT100.csproj | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 cSharp-source/Solution/3-Bucket/HOT100/HOT100.csproj diff --git a/cSharp-source/Solution/3-Bucket/HOT100/HOT100.csproj b/cSharp-source/Solution/3-Bucket/HOT100/HOT100.csproj new file mode 100644 index 0000000..eb2460e --- /dev/null +++ b/cSharp-source/Solution/3-Bucket/HOT100/HOT100.csproj @@ -0,0 +1,9 @@ + + + + net6.0 + enable + enable + + + -- Gitee From 59ef07175ede618db2161a3b0d3579c86f4fabed Mon Sep 17 00:00:00 2001 From: zhousl Date: Fri, 28 Oct 2022 15:20:32 +0800 Subject: [PATCH 31/31] [#update] gitgnore --- .gitignore | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 58b35fc..619bc68 100644 --- a/.gitignore +++ b/.gitignore @@ -109,4 +109,7 @@ ModelManifest.xml #zzzili v15/ -.gitignore \ No newline at end of file +.gitignore + +#custom +.vs/ \ No newline at end of file -- Gitee