diff --git a/.gitignore b/.gitignore index c23a0b3185ff8dc63fb7d34a592d37aed0cb9c27..619bc68a2f0b24f9a33f7de0a90daa95a271c784 100644 --- a/.gitignore +++ b/.gitignore @@ -70,12 +70,21 @@ ipch/ *.psess *.vsp *.vspx +*.v2 +*.v5 +*.v1 +*.testlog +*.manifest +*.vsidx +*.lock # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper* +*.iml +*.xml # NCrunch *.ncrunch* @@ -100,4 +109,7 @@ ModelManifest.xml #zzzili v15/ -.gitignore \ No newline at end of file +.gitignore + +#custom +.vs/ \ No newline at end of file diff --git a/cSharp-source/Solution/.editorconfig b/cSharp-source/Solution/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..9ecd26b81c319d690a5ab57db34b8c95163bda0a --- /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/AlgorithmTest/AlgorithmTest.csproj b/cSharp-source/Solution/0-Test/AlgorithmTest/AlgorithmTest.csproj similarity index 55% rename from cSharp-source/Solution/AlgorithmTest/AlgorithmTest.csproj rename to cSharp-source/Solution/0-Test/AlgorithmTest/AlgorithmTest.csproj index 77fc367c0e847c5c2e62fb0a9085d719079340c8..36e7d7a68e874dcea757ba212978652730689742 100644 --- a/cSharp-source/Solution/AlgorithmTest/AlgorithmTest.csproj +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/AlgorithmTest.csproj @@ -24,7 +24,16 @@ - + + + + + + + + + + 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 0000000000000000000000000000000000000000..a41e65512034db6b22efb2bf28512ac5917330d6 --- /dev/null +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/ArrayTest.cs @@ -0,0 +1,37 @@ +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/StringTest.cs b/cSharp-source/Solution/0-Test/AlgorithmTest/StringTest.cs new file mode 100644 index 0000000000000000000000000000000000000000..77dfce557e53513f651d767096990391d2bf2292 --- /dev/null +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/StringTest.cs @@ -0,0 +1,39 @@ +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()); + } + + [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()); + } + + [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/0-Test/AlgorithmTest/TreeTest.cs b/cSharp-source/Solution/0-Test/AlgorithmTest/TreeTest.cs new file mode 100644 index 0000000000000000000000000000000000000000..6fb0b4c2252e2ab363e73f952e831194dfa9bac0 --- /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 new file mode 100644 index 0000000000000000000000000000000000000000..9a7b58c5206ace9bdf2692d08d2941d7b2c9aefa --- /dev/null +++ b/cSharp-source/Solution/0-Test/AlgorithmTest/Usings.cs @@ -0,0 +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/ArraySection/ArraySection.csproj b/cSharp-source/Solution/1-Basic/ArraySection/ArraySection.csproj similarity index 85% rename from cSharp-source/Solution/ArraySection/ArraySection.csproj rename to cSharp-source/Solution/1-Basic/ArraySection/ArraySection.csproj index b9de0634b4b32337f6558b6863b7284bce39f43f..eb2460e910fa21c0fb88747ca553b619fb62b722 100644 --- a/cSharp-source/Solution/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/ArraySection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs similarity index 46% rename from cSharp-source/Solution/ArraySection/DayQuestion.cs rename to cSharp-source/Solution/1-Basic/ArraySection/DayQuestion.cs index b6cc4913dac4a5583d2193bcf6018e4546a5b62b..4a5df351d8be6c763c9a85161978aaf4c58dbc02 100644 --- a/cSharp-source/Solution/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,8 +274,302 @@ 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 + + // 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]]) + 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; + + 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 + + #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 + + #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. + * + * 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 + + #region day 8.9 + + /* + * 1413. Minimum Value to Get Positive Step by Step Sum + */ + 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 + + #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 + + #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; + } + + #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; } diff --git a/cSharp-source/Solution/ArraySection/GlobalUsings.cs b/cSharp-source/Solution/1-Basic/ArraySection/GlobalUsings.cs similarity index 100% rename from cSharp-source/Solution/ArraySection/GlobalUsings.cs rename to cSharp-source/Solution/1-Basic/ArraySection/GlobalUsings.cs diff --git a/cSharp-source/Solution/ArraySection/Matrix.cs b/cSharp-source/Solution/1-Basic/ArraySection/Matrix.cs similarity index 67% rename from cSharp-source/Solution/ArraySection/Matrix.cs rename to cSharp-source/Solution/1-Basic/ArraySection/Matrix.cs index 264373d8552d5bf9fb0e619ea08ca483932fc522..d975ea685d36dc49a1f0e3d17638bf6e44fcd73e 100644 --- a/cSharp-source/Solution/ArraySection/Matrix.cs +++ b/cSharp-source/Solution/1-Basic/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 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 0000000000000000000000000000000000000000..bc809878d78b8cddbbce866d3b077fb284dcd661 --- /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/LinkSection/LinkRemove.cs b/cSharp-source/Solution/1-Basic/LinkSection/LinkRemove.cs similarity index 100% rename from cSharp-source/Solution/LinkSection/LinkRemove.cs rename to cSharp-source/Solution/1-Basic/LinkSection/LinkRemove.cs 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 0000000000000000000000000000000000000000..9bd7357141813cb135cdc4c475be5689716ca652 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/LinkSection/LinkSection.csproj @@ -0,0 +1,17 @@ + + + + net6.0 + enable + enable + + + + 1701;1702;8600;8601 + + + + 1701;1702;8600;8601 + + + diff --git a/cSharp-source/Solution/LinkSection/ListNode.cs b/cSharp-source/Solution/1-Basic/LinkSection/ListNode.cs similarity index 100% rename from cSharp-source/Solution/LinkSection/ListNode.cs rename to cSharp-source/Solution/1-Basic/LinkSection/ListNode.cs 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 0000000000000000000000000000000000000000..c824ac7262e0db6fdf27aa8f7b30e633a10f1649 --- /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/1-Basic/QueueSection/DayQuestion.cs b/cSharp-source/Solution/1-Basic/QueueSection/DayQuestion.cs new file mode 100644 index 0000000000000000000000000000000000000000..d70b91abd59420ec1d3b73afe05a51fd035f62fc --- /dev/null +++ b/cSharp-source/Solution/1-Basic/QueueSection/DayQuestion.cs @@ -0,0 +1,69 @@ +namespace QueueSection; + +public class DayQuestion +{ + +} + +#region day 8.1 + +// 剑指 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); + } +} + +#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/cSharp-source/Solution/1-Basic/QueueSection/MyCircularDeque.cs b/cSharp-source/Solution/1-Basic/QueueSection/MyCircularDeque.cs new file mode 100644 index 0000000000000000000000000000000000000000..217f938c742761d8918bf9f840c06d647cc898e8 --- /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/LinkSection/LinkSection.csproj b/cSharp-source/Solution/1-Basic/QueueSection/QueueSection.csproj similarity index 85% rename from cSharp-source/Solution/LinkSection/LinkSection.csproj rename to cSharp-source/Solution/1-Basic/QueueSection/QueueSection.csproj index b9de0634b4b32337f6558b6863b7284bce39f43f..eb2460e910fa21c0fb88747ca553b619fb62b722 100644 --- a/cSharp-source/Solution/LinkSection/LinkSection.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/DayQuestions.cs b/cSharp-source/Solution/1-Basic/StackSection/DayQuestions.cs new file mode 100644 index 0000000000000000000000000000000000000000..2cf6e0337b8ee2c18efc79091f4434e00c56948a --- /dev/null +++ b/cSharp-source/Solution/1-Basic/StackSection/DayQuestions.cs @@ -0,0 +1,82 @@ +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 + + #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/StackSection/StackSection.csproj b/cSharp-source/Solution/1-Basic/StackSection/StackSection.csproj new file mode 100644 index 0000000000000000000000000000000000000000..132c02c59c23649c0b1ecd3906af6a82a3852d7a --- /dev/null +++ b/cSharp-source/Solution/1-Basic/StackSection/StackSection.csproj @@ -0,0 +1,9 @@ + + + + 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 0000000000000000000000000000000000000000..85b08343f21e3fac3c7fec5cf5fd57dd6d739467 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/StringSection/DayQuestion.cs @@ -0,0 +1,233 @@ +using System.Text; + +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 + + #region day 7.29 + + //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 + + #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 + + #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 + + #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 + + #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/TreeSection/TreeSection.csproj b/cSharp-source/Solution/1-Basic/StringSection/StringSection.csproj similarity index 85% rename from cSharp-source/Solution/TreeSection/TreeSection.csproj rename to cSharp-source/Solution/1-Basic/StringSection/StringSection.csproj index b9de0634b4b32337f6558b6863b7284bce39f43f..eb2460e910fa21c0fb88747ca553b619fb62b722 100644 --- a/cSharp-source/Solution/TreeSection/TreeSection.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/CBTInserter.cs b/cSharp-source/Solution/1-Basic/TreeSection/CBTInserter.cs new file mode 100644 index 0000000000000000000000000000000000000000..5bc7ba7a817fc38843c02f51a1c33e38b3e55385 --- /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 0000000000000000000000000000000000000000..878f92da4ee4674c5357fbc8651637617888794a --- /dev/null +++ b/cSharp-source/Solution/1-Basic/TreeSection/DayQuestion.cs @@ -0,0 +1,286 @@ +#pragma warning disable CS8625 +namespace TreeSection; + +public class DayQuestion +{ + #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.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. + //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 + + #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; + } + + var queue = new Queue(); + queue.Enqueue(root); + + 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); + } + } + + 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 + + #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 + + /* + 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; + } + + var max = int.MinValue; + var index = 0; + for (var 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 + + #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/TreeSection/FindTreeNode.cs b/cSharp-source/Solution/1-Basic/TreeSection/FindTreeNode.cs similarity index 100% rename from cSharp-source/Solution/TreeSection/FindTreeNode.cs rename to cSharp-source/Solution/1-Basic/TreeSection/FindTreeNode.cs diff --git a/cSharp-source/Solution/TreeSection/TreeNode.cs b/cSharp-source/Solution/1-Basic/TreeSection/TreeNode.cs similarity index 100% rename from cSharp-source/Solution/TreeSection/TreeNode.cs rename to cSharp-source/Solution/1-Basic/TreeSection/TreeNode.cs 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 0000000000000000000000000000000000000000..70877dd0c10a84eda1cf9496b9e0008dc1687f72 --- /dev/null +++ b/cSharp-source/Solution/1-Basic/TreeSection/TreeSection.csproj @@ -0,0 +1,17 @@ + + + + net6.0 + enable + enable + + + + 1701;1702;8600;8650 + + + + 1701;1702;8600;8650 + + + diff --git a/cSharp-source/Solution/DPSection/DPSection.csproj b/cSharp-source/Solution/2-External/DPSection/DPSection.csproj similarity index 86% rename from cSharp-source/Solution/DPSection/DPSection.csproj rename to cSharp-source/Solution/2-External/DPSection/DPSection.csproj index 74abf5c9766499f4fd79d4a9398f619d39c2e45e..132c02c59c23649c0b1ecd3906af6a82a3852d7a 100644 --- a/cSharp-source/Solution/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/DPSection/DayQuestion.cs b/cSharp-source/Solution/2-External/DPSection/DayQuestion.cs similarity index 84% rename from cSharp-source/Solution/DPSection/DayQuestion.cs rename to cSharp-source/Solution/2-External/DPSection/DayQuestion.cs index 6d11dbd4fc3ebe70bbe07aaafa157bf37399b962..7fd8046bf253d734e69d0546dccde49ff95fa7ac 100644 --- a/cSharp-source/Solution/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/EncodeSection/DayQuestion.cs b/cSharp-source/Solution/2-External/EncodeSection/DayQuestion.cs similarity index 100% rename from cSharp-source/Solution/EncodeSection/DayQuestion.cs rename to cSharp-source/Solution/2-External/EncodeSection/DayQuestion.cs diff --git a/cSharp-source/Solution/EncodeSection/EncodeSection.csproj b/cSharp-source/Solution/2-External/EncodeSection/EncodeSection.csproj similarity index 100% rename from cSharp-source/Solution/EncodeSection/EncodeSection.csproj rename to cSharp-source/Solution/2-External/EncodeSection/EncodeSection.csproj 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 0000000000000000000000000000000000000000..9e39dff672d4a366c8c10a5730c59fa639a18d6b --- /dev/null +++ b/cSharp-source/Solution/2-External/MathSection/DayQuestion.cs @@ -0,0 +1,39 @@ +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). + + private int shortLens = -1; + + public bool ValidSquare(int[] p1, int[] p2, int[] p3, int[] p4) + { + 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/cSharp-source/Solution/2-External/MathSection/MathSection.csproj b/cSharp-source/Solution/2-External/MathSection/MathSection.csproj new file mode 100644 index 0000000000000000000000000000000000000000..132c02c59c23649c0b1ecd3906af6a82a3852d7a --- /dev/null +++ b/cSharp-source/Solution/2-External/MathSection/MathSection.csproj @@ -0,0 +1,9 @@ + + + + net6.0 + enable + enable + + + 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 0000000000000000000000000000000000000000..b29b2e1c996a94507a74d08fa2814b794fb59515 --- /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/OrderQueue.cs b/cSharp-source/Solution/2-External/OrderSetSection/OrderQueue.cs new file mode 100644 index 0000000000000000000000000000000000000000..d80e05288c06e6c8f469787a0ee53800d59732d7 --- /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/cSharp-source/Solution/2-External/OrderSetSection/OrderSetSection.csproj b/cSharp-source/Solution/2-External/OrderSetSection/OrderSetSection.csproj new file mode 100644 index 0000000000000000000000000000000000000000..132c02c59c23649c0b1ecd3906af6a82a3852d7a --- /dev/null +++ b/cSharp-source/Solution/2-External/OrderSetSection/OrderSetSection.csproj @@ -0,0 +1,9 @@ + + + + net6.0 + enable + enable + + + 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 0000000000000000000000000000000000000000..a0c7324196f9934c00af1007037a3df44fa77738 --- /dev/null +++ b/cSharp-source/Solution/2-External/OrderSetSection/OrderedStream.cs @@ -0,0 +1,34 @@ +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. + */ + + 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) + { + IList ans = new List(); + arr[idKey] = value; + while (arr[_ptr].Length == 5) ans.Add(arr[_ptr++]); + return ans; + } +} 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 0000000000000000000000000000000000000000..041d19edf77228a09a9045cc19802732aa41ad64 --- /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/TrieSection/DayQuestion.cs b/cSharp-source/Solution/2-External/TrieSection/DayQuestion.cs similarity index 100% rename from cSharp-source/Solution/TrieSection/DayQuestion.cs rename to cSharp-source/Solution/2-External/TrieSection/DayQuestion.cs diff --git a/cSharp-source/Solution/TrieSection/TrieSection.csproj b/cSharp-source/Solution/2-External/TrieSection/TrieSection.csproj similarity index 85% rename from cSharp-source/Solution/TrieSection/TrieSection.csproj rename to cSharp-source/Solution/2-External/TrieSection/TrieSection.csproj index b9de0634b4b32337f6558b6863b7284bce39f43f..eb2460e910fa21c0fb88747ca553b619fb62b722 100644 --- a/cSharp-source/Solution/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 0000000000000000000000000000000000000000..f721f3cd4c6548ccfbbc8aeb6a5ecc177bd9576f --- /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/HOT100.csproj b/cSharp-source/Solution/3-Bucket/HOT100/HOT100.csproj new file mode 100644 index 0000000000000000000000000000000000000000..eb2460e910fa21c0fb88747ca553b619fb62b722 --- /dev/null +++ b/cSharp-source/Solution/3-Bucket/HOT100/HOT100.csproj @@ -0,0 +1,9 @@ + + + + net6.0 + enable + enable + + + 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 0000000000000000000000000000000000000000..8715956562324b6b4eb6edd0303def5c8561eb77 --- /dev/null +++ b/cSharp-source/Solution/3-Bucket/HOT100/ListNode.cs @@ -0,0 +1,14 @@ +#pragma warning disable CS8625 +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/AlgorithmTest/ArrayTest.cs b/cSharp-source/Solution/AlgorithmTest/ArrayTest.cs deleted file mode 100644 index dbab50cb6eeeb37251ee01dd26cdd0a94a625ea9..0000000000000000000000000000000000000000 --- 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 8e2783342b72b415ae174bb4952330aac7a5ef49..0000000000000000000000000000000000000000 --- 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/Program.cs b/cSharp-source/Solution/ArraySection/Program.cs deleted file mode 100644 index 837131c21c3c4803953cdcfd2c559fcc692caa96..0000000000000000000000000000000000000000 --- 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/Program.cs b/cSharp-source/Solution/DPSection/Program.cs deleted file mode 100644 index 837131c21c3c4803953cdcfd2c559fcc692caa96..0000000000000000000000000000000000000000 --- 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/LinkSection/Program.cs b/cSharp-source/Solution/LinkSection/Program.cs deleted file mode 100644 index 837131c21c3c4803953cdcfd2c559fcc692caa96..0000000000000000000000000000000000000000 --- 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/Solution.sln b/cSharp-source/Solution/Solution.sln index 90bc6bfa3262f4d73b0f60b62bad57df69580051..6209d91f39ffe951b8f04ad39214462f7e301a0f 100644 --- a/cSharp-source/Solution/Solution.sln +++ b/cSharp-source/Solution/Solution.sln @@ -3,25 +3,44 @@ 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("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AlgorithmTest", "0-Test\AlgorithmTest\AlgorithmTest.csproj", "{6341CEA4-1D22-4330-984A-28C5C9F1A102}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EncodeSection", "EncodeSection\EncodeSection.csproj", "{5D630232-7215-4FCF-A5DA-7B943B61BD58}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "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("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "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("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "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("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StackSection", "1-Basic\StackSection\StackSection.csproj", "{26C5CAF2-FDFD-48C4-97C8-1214AC963D8D}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StringSection", "1-Basic\StringSection\StringSection.csproj", "{AF63F2C5-34DC-4E7B-8B79-C6F3D7A0482D}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TreeSection", "1-Basic\TreeSection\TreeSection.csproj", "{E8F30DCA-D2B4-41DC-8AB0-54A70EFC90DE}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DPSection", "2-External\DPSection\DPSection.csproj", "{C8DEE532-AAAA-40FC-962E-F21DAA6C8C6F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrieSection", "TrieSection\TrieSection.csproj", "{6F24B5FF-4F1A-4E65-9959-118DAA01C460}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EncodeSection", "2-External\EncodeSection\EncodeSection.csproj", "{F001E030-28DE-4C40-B424-C9B50100FEC7}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OrderSetSection", "2-External\OrderSetSection\OrderSetSection.csproj", "{35FD5694-B1B8-4FD5-8FA8-896243F99EAB}" +EndProject +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 +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 @@ -29,48 +48,78 @@ 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 + {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 + {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 + {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 EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {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} + {966165B5-25B4-406E-A2F4-5F1B87E0F0BE} = {5D2E938C-2618-4DD9-A439-F193655266A0} + {862F0319-D690-43CF-B011-952A64D08E41} = {A93CFA6A-A24F-4A88-A7C1-D456A8C3A204} + 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} - {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} - EndGlobalSection EndGlobal diff --git a/cSharp-source/Solution/TreeSection/DayQuestion.cs b/cSharp-source/Solution/TreeSection/DayQuestion.cs deleted file mode 100644 index d9ad04ce5a68e900f65755ad6dd5b0d5503e6744..0000000000000000000000000000000000000000 --- a/cSharp-source/Solution/TreeSection/DayQuestion.cs +++ /dev/null @@ -1,62 +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 -} diff --git a/cSharp-source/Solution/TreeSection/Program.cs b/cSharp-source/Solution/TreeSection/Program.cs deleted file mode 100644 index 837131c21c3c4803953cdcfd2c559fcc692caa96..0000000000000000000000000000000000000000 --- 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/TrieSection/Program.cs b/cSharp-source/Solution/TrieSection/Program.cs deleted file mode 100644 index 837131c21c3c4803953cdcfd2c559fcc692caa96..0000000000000000000000000000000000000000 --- 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/go-source/src/0-test/algorithm_test.go b/go-source/src/0-test/algorithm_test.go new file mode 100644 index 0000000000000000000000000000000000000000..d6e944639a1cb490e50bfd59f891f685d3d6c0f2 --- /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 771f99598fb12d4689556448b03d89e51f170f19..0cae9c1ab22950229623add95652316747fa0bce 100644 --- a/go-source/src/1-basic/arraySection/dayQuestion.go +++ b/go-source/src/1-basic/arraySection/dayQuestion.go @@ -8,27 +8,17 @@ 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 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 +139,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) @@ -170,3 +156,82 @@ 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 +} + +/* 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 +} + +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/arraySection/matrix.go b/go-source/src/1-basic/arraySection/matrix.go index efadcbefcca89777887f5efbd5d89ca27eaa2dea..6887265d20ab8ff9e522c0361d9b28a155ccc4ae 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/linkSection/designLink.go b/go-source/src/1-basic/linkSection/designLink.go new file mode 100644 index 0000000000000000000000000000000000000000..94e33b56e2a41ebbfbf8cf10bfa5620aae5e557f --- /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 84e40ebd7c1e8a3d757ad36f7cb7ac3eb32f68ec..c48f0dded09fd52f7189a329a24df2d61f5a9912 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 { @@ -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 +} 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 0000000000000000000000000000000000000000..70a92370160a9069eb3909533551ec31f1824564 --- /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 +} 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 0000000000000000000000000000000000000000..ad1941f5452c9aff7fd0a08a758f3c5ee16d9902 --- /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 0000000000000000000000000000000000000000..90e58f6ec9d00e40793c794d3216946829a6d83c --- /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)) +} 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 0000000000000000000000000000000000000000..61c4110837f8c2842a2edaacf4b55b3b1f5dd2f8 --- /dev/null +++ b/go-source/src/1-basic/stackSection/dayQuestion.go @@ -0,0 +1,31 @@ +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/1-basic/stringSection/dayQuestion.go b/go-source/src/1-basic/stringSection/dayQuestion.go new file mode 100644 index 0000000000000000000000000000000000000000..fd94d539dd5cf6147c4cc305795d1952c71d8967 --- /dev/null +++ b/go-source/src/1-basic/stringSection/dayQuestion.go @@ -0,0 +1,95 @@ +package stringSection + +import ( + "strconv" + "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" +} + +/* +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" +} + +/* +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/1-basic/treeSection/cbtInserter.go b/go-source/src/1-basic/treeSection/cbtInserter.go new file mode 100644 index 0000000000000000000000000000000000000000..6ce6907235bf13f7f34830934c4e0a85c1e5f0df --- /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 +} diff --git a/go-source/src/1-basic/treeSection/dayQuestion.go b/go-source/src/1-basic/treeSection/dayQuestion.go index 6456a372449ca7affdb7d0d13b5da02349fd5b9c..e3eaf3c8f416ad5bf7a089b97717ec40c39075c6 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 @@ -33,6 +33,53 @@ 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 +} + +//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 diff --git a/go-source/src/1-basic/treeSection/findTreeNode.go b/go-source/src/1-basic/treeSection/findTreeNode.go index d1a3b78646a400bd6b7696dc94eadee8f2f14347..ca5a127974e36fa6df99d2f0e3c90d7a251caaa3 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 { diff --git a/go-source/src/2-external/encodeSection/dayQuestion.go b/go-source/src/2-external/encodeSection/dayQuestion.go index 69fcbcc0951e2b287cc5c0297a9ddc93c7c07356..7b34d613388c5f1efe2a329036fbad8603dc16c2 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/mathSection/dayQuestion.go b/go-source/src/2-external/mathSection/dayQuestion.go new file mode 100644 index 0000000000000000000000000000000000000000..52b5079a9443d7f3201415536c34ec1bcff65074 --- /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 +} 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 0000000000000000000000000000000000000000..ea4d33ad6d4d455133c6fbdfab8fcf2985c1ccae --- /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 +} 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 0000000000000000000000000000000000000000..7f4a68915d79ccccd5b6330d10ce1807ed04a0be --- /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 + } +} 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 0000000000000000000000000000000000000000..8c33b104c9f776af12504ba0b426d3c0eb82cf0f --- /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, "") +} diff --git a/go-source/src/main.go b/go-source/src/main.go index 01f9435207df4aec218ea545765e7aa9bbd1a9a3..3266d2a99fa9fca293f8cdd26924b14f1d5c87c7 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")) }