diff --git a/.travis.yml b/.travis.yml index 8ea1ce316..35679106c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,7 +7,6 @@ go: branches: only: - master - - stable script: - go get -t -v ./... diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 000000000..3f8bab8b0 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,17 @@ +{ + // 使用 IntelliSense 了解相关属性。 + // 悬停以查看现有属性的描述。 + // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Launch", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${fileDirname}", + "env": {}, + "args": [] + } + ] +} \ No newline at end of file diff --git a/Algorithms/0002. Add Two Numbers/2. Add Two Numbers.go b/Algorithms/0002. Add Two Numbers/2. Add Two Numbers.go index 0b85531e4..5854bf659 100644 --- a/Algorithms/0002. Add Two Numbers/2. Add Two Numbers.go +++ b/Algorithms/0002. Add Two Numbers/2. Add Two Numbers.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { @@ -7,6 +14,7 @@ package leetcode * Next *ListNode * } */ + func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { if l1 == nil || l2 == nil { return nil diff --git a/Algorithms/0002. Add Two Numbers/2. Add Two Numbers_test.go b/Algorithms/0002. Add Two Numbers/2. Add Two Numbers_test.go index 304ffa763..2660d4dde 100644 --- a/Algorithms/0002. Add Two Numbers/2. Add Two Numbers_test.go +++ b/Algorithms/0002. Add Two Numbers/2. Add Two Numbers_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question2 struct { @@ -73,7 +75,7 @@ func Test_Problem2(t *testing.T) { for _, q := range qs { _, p := q.ans2, q.para2 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(addTwoNumbers(S2l(p.one), S2l(p.another)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(addTwoNumbers(structures.Ints2List(p.one), structures.Ints2List(p.another)))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0003. Longest Substring Without Repeating Characters/3. Longest Substring Without Repeating Characters.go b/Algorithms/0003. Longest Substring Without Repeating Characters/3. Longest Substring Without Repeating Characters.go index 635db849c..2a722007f 100644 --- a/Algorithms/0003. Longest Substring Without Repeating Characters/3. Longest Substring Without Repeating Characters.go +++ b/Algorithms/0003. Longest Substring Without Repeating Characters/3. Longest Substring Without Repeating Characters.go @@ -20,3 +20,10 @@ func lengthOfLongestSubstring(s string) int { } return result } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0004. Median of Two Sorted Arrays/4. Median of Two Sorted Arrays.go b/Algorithms/0004. Median of Two Sorted Arrays/4. Median of Two Sorted Arrays.go index 02a3abe67..098e34721 100644 --- a/Algorithms/0004. Median of Two Sorted Arrays/4. Median of Two Sorted Arrays.go +++ b/Algorithms/0004. Median of Two Sorted Arrays/4. Median of Two Sorted Arrays.go @@ -41,3 +41,17 @@ func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { } return float64(midLeft+midRight) / 2 } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/0019. Remove Nth Node From End of List/19. Remove Nth Node From End of List.go b/Algorithms/0019. Remove Nth Node From End of List/19. Remove Nth Node From End of List.go index 63a4e285b..a4d4d18f9 100644 --- a/Algorithms/0019. Remove Nth Node From End of List/19. Remove Nth Node From End of List.go +++ b/Algorithms/0019. Remove Nth Node From End of List/19. Remove Nth Node From End of List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0019. Remove Nth Node From End of List/19. Remove Nth Node From End of List_test.go b/Algorithms/0019. Remove Nth Node From End of List/19. Remove Nth Node From End of List_test.go index b8303f0f9..bee4e53dd 100644 --- a/Algorithms/0019. Remove Nth Node From End of List/19. Remove Nth Node From End of List_test.go +++ b/Algorithms/0019. Remove Nth Node From End of List/19. Remove Nth Node From End of List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question19 struct { @@ -50,23 +52,13 @@ func Test_Problem19(t *testing.T) { para19{[]int{1, 2, 3, 4, 5}, 5}, ans19{[]int{2, 3, 4, 5}}, }, - - question19{ - para19{[]int{1, 2, 3, 4, 5}, 0}, - ans19{[]int{1, 2, 3, 4, 5}}, - }, - - question19{ - para19{[]int{1, 2, 3, 4, 5}, 10}, - ans19{[]int{1, 2, 3, 4, 5}}, - }, } fmt.Printf("------------------------Leetcode Problem 19------------------------\n") for _, q := range qs { _, p := q.ans19, q.para19 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(removeNthFromEnd(S2l(p.one), p.n))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(removeNthFromEnd(structures.Ints2List(p.one), p.n))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0021. Merge Two Sorted Lists/21. Merge Two Sorted Lists.go b/Algorithms/0021. Merge Two Sorted Lists/21. Merge Two Sorted Lists.go index e3a71d9ce..53531b2b4 100644 --- a/Algorithms/0021. Merge Two Sorted Lists/21. Merge Two Sorted Lists.go +++ b/Algorithms/0021. Merge Two Sorted Lists/21. Merge Two Sorted Lists.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0021. Merge Two Sorted Lists/21. Merge Two Sorted Lists_test.go b/Algorithms/0021. Merge Two Sorted Lists/21. Merge Two Sorted Lists_test.go index 499b1b5b5..8ca0b481c 100644 --- a/Algorithms/0021. Merge Two Sorted Lists/21. Merge Two Sorted Lists_test.go +++ b/Algorithms/0021. Merge Two Sorted Lists/21. Merge Two Sorted Lists_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question21 struct { @@ -73,7 +75,7 @@ func Test_Problem21(t *testing.T) { for _, q := range qs { _, p := q.ans21, q.para21 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(mergeTwoLists(S2l(p.one), S2l(p.another)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(mergeTwoLists(structures.Ints2List(p.one), structures.Ints2List(p.another)))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0023. Merge k Sorted Lists/23. Merge k Sorted Lists.go b/Algorithms/0023. Merge k Sorted Lists/23. Merge k Sorted Lists.go index 5ae46b400..c25317b2f 100644 --- a/Algorithms/0023. Merge k Sorted Lists/23. Merge k Sorted Lists.go +++ b/Algorithms/0023. Merge k Sorted Lists/23. Merge k Sorted Lists.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0023. Merge k Sorted Lists/23. Merge k Sorted Lists_test.go b/Algorithms/0023. Merge k Sorted Lists/23. Merge k Sorted Lists_test.go index 9f7d1ad19..bb66cad4a 100644 --- a/Algorithms/0023. Merge k Sorted Lists/23. Merge k Sorted Lists_test.go +++ b/Algorithms/0023. Merge k Sorted Lists/23. Merge k Sorted Lists_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question23 struct { @@ -94,9 +96,9 @@ func Test_Problem23(t *testing.T) { for _, q := range qs { var ls []*ListNode for _, qq := range q.para23.one { - ls = append(ls, S2l(qq)) + ls = append(ls, structures.Ints2List(qq)) } - fmt.Printf("【input】:%v 【output】:%v\n", q.para23.one, L2s(mergeKLists(ls))) + fmt.Printf("【input】:%v 【output】:%v\n", q.para23.one, structures.List2Ints(mergeKLists(ls))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0024. Swap Nodes in Pairs/24. Swap Nodes in Pairs.go b/Algorithms/0024. Swap Nodes in Pairs/24. Swap Nodes in Pairs.go index 467adb751..1dc9e41de 100644 --- a/Algorithms/0024. Swap Nodes in Pairs/24. Swap Nodes in Pairs.go +++ b/Algorithms/0024. Swap Nodes in Pairs/24. Swap Nodes in Pairs.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0024. Swap Nodes in Pairs/24. Swap Nodes in Pairs_test.go b/Algorithms/0024. Swap Nodes in Pairs/24. Swap Nodes in Pairs_test.go index 5cf86fcfa..56ff303c6 100644 --- a/Algorithms/0024. Swap Nodes in Pairs/24. Swap Nodes in Pairs_test.go +++ b/Algorithms/0024. Swap Nodes in Pairs/24. Swap Nodes in Pairs_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question24 struct { @@ -53,39 +55,7 @@ func Test_Problem24(t *testing.T) { for _, q := range qs { _, p := q.ans24, q.para24 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(swapPairs(S2l(p.one)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(swapPairs(structures.Ints2List(p.one)))) } fmt.Printf("\n\n\n") } - -// convert *ListNode to []int -func L2s(head *ListNode) []int { - res := []int{} - - for head != nil { - res = append(res, head.Val) - head = head.Next - } - - return res -} - -// convert []int to *ListNode -func S2l(nums []int) *ListNode { - if len(nums) == 0 { - return nil - } - - res := &ListNode{ - Val: nums[0], - } - temp := res - for i := 1; i < len(nums); i++ { - temp.Next = &ListNode{ - Val: nums[i], - } - temp = temp.Next - } - - return res -} diff --git a/Algorithms/0025. Reverse Nodes in k Group/25. Reverse Nodes in k Group.go b/Algorithms/0025. Reverse Nodes in k Group/25. Reverse Nodes in k Group.go index 41ed9237d..d206f0761 100644 --- a/Algorithms/0025. Reverse Nodes in k Group/25. Reverse Nodes in k Group.go +++ b/Algorithms/0025. Reverse Nodes in k Group/25. Reverse Nodes in k Group.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0025. Reverse Nodes in k Group/25. Reverse Nodes in k Group_test.go b/Algorithms/0025. Reverse Nodes in k Group/25. Reverse Nodes in k Group_test.go index 9654a24d1..34baf9367 100644 --- a/Algorithms/0025. Reverse Nodes in k Group/25. Reverse Nodes in k Group_test.go +++ b/Algorithms/0025. Reverse Nodes in k Group/25. Reverse Nodes in k Group_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question25 struct { @@ -48,7 +50,7 @@ func Test_Problem25(t *testing.T) { for _, q := range qs { _, p := q.ans25, q.para25 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(reverseKGroup(S2l(p.one), p.two))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(reverseKGroup(structures.Ints2List(p.one), p.two))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0029. Divide Two Integers/29. Divide Two Integers.go b/Algorithms/0029. Divide Two Integers/29. Divide Two Integers.go index faeed5cdf..21fb06960 100644 --- a/Algorithms/0029. Divide Two Integers/29. Divide Two Integers.go +++ b/Algorithms/0029. Divide Two Integers/29. Divide Two Integers.go @@ -91,3 +91,10 @@ func divide1(divided int, divisor int) int { } return sign * result } + +func abs(a int) int { + if a > 0 { + return a + } + return -a +} diff --git a/Algorithms/0053. Maximum Subarray/53. Maximum Subarray.go b/Algorithms/0053. Maximum Subarray/53. Maximum Subarray.go index 03e3e2270..8db251a2d 100644 --- a/Algorithms/0053. Maximum Subarray/53. Maximum Subarray.go +++ b/Algorithms/0053. Maximum Subarray/53. Maximum Subarray.go @@ -39,3 +39,10 @@ func maxSubArray1(nums []int) int { } return maxSum } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0054. Spiral Matrix/54. Spiral Matrix.go b/Algorithms/0054. Spiral Matrix/54. Spiral Matrix.go index 9e6eca7c3..ae2ae1160 100644 --- a/Algorithms/0054. Spiral Matrix/54. Spiral Matrix.go +++ b/Algorithms/0054. Spiral Matrix/54. Spiral Matrix.go @@ -81,10 +81,10 @@ func spiralOrder2(matrix [][]int) []int { } // top、left、right、bottom 分别是剩余区域的上、左、右、下的下标 - top, left, bottom, right := 0, 0, m-1, n-1 + top, left, bottom, right := 0, 0, m-1, n-1 count, sum := 0, m*n res := []int{} - + // 外层循环每次遍历一圈 for count < sum { i, j := top, left @@ -93,19 +93,19 @@ func spiralOrder2(matrix [][]int) []int { count++ j++ } - i, j = top + 1, right + i, j = top+1, right for i <= bottom && count < sum { res = append(res, matrix[i][j]) count++ i++ } - i, j = bottom, right - 1 + i, j = bottom, right-1 for j >= left && count < sum { res = append(res, matrix[i][j]) count++ j-- } - i, j = bottom - 1, left + i, j = bottom-1, left for i > top && count < sum { res = append(res, matrix[i][j]) count++ diff --git a/Algorithms/0056. Merge Intervals/56. Merge Intervals.go b/Algorithms/0056. Merge Intervals/56. Merge Intervals.go index 4ce74167d..e529aa3b3 100644 --- a/Algorithms/0056. Merge Intervals/56. Merge Intervals.go +++ b/Algorithms/0056. Merge Intervals/56. Merge Intervals.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// Interval define +type Interval = structures.Interval + /** * Definition for an interval. * type Interval struct { @@ -8,12 +15,6 @@ package leetcode * } */ -// Interval define -type Interval struct { - Start int - End int -} - func merge56(intervals []Interval) []Interval { if len(intervals) == 0 { return intervals diff --git a/Algorithms/0057. Insert Interval/57. Insert Interval.go b/Algorithms/0057. Insert Interval/57. Insert Interval.go index fa5422e36..591ee3dfd 100644 --- a/Algorithms/0057. Insert Interval/57. Insert Interval.go +++ b/Algorithms/0057. Insert Interval/57. Insert Interval.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// Interval define +type Interval = structures.Interval + /** * Definition for an interval. * type Interval struct { @@ -32,3 +39,17 @@ func insert(intervals []Interval, newInterval Interval) []Interval { } return res } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/0061. Rotate List/61. Rotate List.go b/Algorithms/0061. Rotate List/61. Rotate List.go index 2fa6e24d4..a2f584ede 100644 --- a/Algorithms/0061. Rotate List/61. Rotate List.go +++ b/Algorithms/0061. Rotate List/61. Rotate List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0061. Rotate List/61. Rotate List_test.go b/Algorithms/0061. Rotate List/61. Rotate List_test.go index ca0f7cc92..98f82957b 100644 --- a/Algorithms/0061. Rotate List/61. Rotate List_test.go +++ b/Algorithms/0061. Rotate List/61. Rotate List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question61 struct { @@ -62,7 +64,7 @@ func Test_Problem61(t *testing.T) { for _, q := range qs { _, p := q.ans61, q.para61 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(rotateRight(S2l(p.one), p.k))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(rotateRight(structures.Ints2List(p.one), p.k))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0064. Minimum Path Sum/64. Minimum Path Sum.go b/Algorithms/0064. Minimum Path Sum/64. Minimum Path Sum.go index ab706adf4..ea2bcc04d 100644 --- a/Algorithms/0064. Minimum Path Sum/64. Minimum Path Sum.go +++ b/Algorithms/0064. Minimum Path Sum/64. Minimum Path Sum.go @@ -55,3 +55,10 @@ func minPathSum1(grid [][]int) int { } return dp[m-1][n-1] } + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/0078. Subsets/78. Subsets.go b/Algorithms/0078. Subsets/78. Subsets.go index 196376e25..1cca87952 100644 --- a/Algorithms/0078. Subsets/78. Subsets.go +++ b/Algorithms/0078. Subsets/78. Subsets.go @@ -51,9 +51,9 @@ func subsets2(nums []int) [][]int { sum := 1 << uint(len(nums)) for i := 0; i < sum; i++ { stack := []int{} - tmp := i // i 从 000...000 到 111...111 + tmp := i // i 从 000...000 到 111...111 for j := len(nums) - 1; j >= 0; j-- { // 遍历 i 的每一位 - if tmp & 1 == 1 { + if tmp&1 == 1 { stack = append([]int{nums[j]}, stack...) } tmp >>= 1 diff --git a/Algorithms/0082. Remove Duplicates from Sorted List II/82. Remove Duplicates from Sorted List II.go b/Algorithms/0082. Remove Duplicates from Sorted List II/82. Remove Duplicates from Sorted List II.go index 60c2cd92e..1fd719730 100644 --- a/Algorithms/0082. Remove Duplicates from Sorted List II/82. Remove Duplicates from Sorted List II.go +++ b/Algorithms/0082. Remove Duplicates from Sorted List II/82. Remove Duplicates from Sorted List II.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { @@ -66,3 +73,21 @@ func deleteDuplicates2(head *ListNode) *ListNode { head.Next = deleteDuplicates(head.Next) return head } + +func deleteDuplicates(head *ListNode) *ListNode { + cur := head + if head == nil { + return nil + } + if head.Next == nil { + return head + } + for cur.Next != nil { + if cur.Next.Val == cur.Val { + cur.Next = cur.Next.Next + } else { + cur = cur.Next + } + } + return head +} diff --git a/Algorithms/0082. Remove Duplicates from Sorted List II/82. Remove Duplicates from Sorted List II_test.go b/Algorithms/0082. Remove Duplicates from Sorted List II/82. Remove Duplicates from Sorted List II_test.go index ebda8a62d..b9631bde6 100644 --- a/Algorithms/0082. Remove Duplicates from Sorted List II/82. Remove Duplicates from Sorted List II_test.go +++ b/Algorithms/0082. Remove Duplicates from Sorted List II/82. Remove Duplicates from Sorted List II_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question82 struct { @@ -76,7 +78,7 @@ func Test_Problem82(t *testing.T) { for _, q := range qs { _, p := q.ans82, q.para82 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(deleteDuplicates1(S2l(p.one)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(deleteDuplicates1(structures.Ints2List(p.one)))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0083. Remove Duplicates from Sorted List/83. Remove Duplicates from Sorted List.go b/Algorithms/0083. Remove Duplicates from Sorted List/83. Remove Duplicates from Sorted List.go index 5abf64311..4c9e711cc 100644 --- a/Algorithms/0083. Remove Duplicates from Sorted List/83. Remove Duplicates from Sorted List.go +++ b/Algorithms/0083. Remove Duplicates from Sorted List/83. Remove Duplicates from Sorted List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0083. Remove Duplicates from Sorted List/83. Remove Duplicates from Sorted List_test.go b/Algorithms/0083. Remove Duplicates from Sorted List/83. Remove Duplicates from Sorted List_test.go index 54e9507a1..4d1e9fd94 100644 --- a/Algorithms/0083. Remove Duplicates from Sorted List/83. Remove Duplicates from Sorted List_test.go +++ b/Algorithms/0083. Remove Duplicates from Sorted List/83. Remove Duplicates from Sorted List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question83 struct { @@ -46,7 +48,7 @@ func Test_Problem83(t *testing.T) { for _, q := range qs { _, p := q.ans83, q.para83 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(deleteDuplicates(S2l(p.one)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(deleteDuplicates(structures.Ints2List(p.one)))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0084. Largest Rectangle in Histogram/84. Largest Rectangle in Histogram.go b/Algorithms/0084. Largest Rectangle in Histogram/84. Largest Rectangle in Histogram.go index 3c56534d5..6b782978a 100644 --- a/Algorithms/0084. Largest Rectangle in Histogram/84. Largest Rectangle in Histogram.go +++ b/Algorithms/0084. Largest Rectangle in Histogram/84. Largest Rectangle in Histogram.go @@ -30,3 +30,10 @@ func largestRectangleArea(heights []int) int { } return maxArea } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0086. Partition List/86. Partition List.go b/Algorithms/0086. Partition List/86. Partition List.go index 4d4b40c32..d031e884c 100644 --- a/Algorithms/0086. Partition List/86. Partition List.go +++ b/Algorithms/0086. Partition List/86. Partition List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0086. Partition List/86. Partition List_test.go b/Algorithms/0086. Partition List/86. Partition List_test.go index 31a23cfb1..2ea1d618b 100644 --- a/Algorithms/0086. Partition List/86. Partition List_test.go +++ b/Algorithms/0086. Partition List/86. Partition List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question86 struct { @@ -67,7 +69,7 @@ func Test_Problem86(t *testing.T) { for _, q := range qs { _, p := q.ans86, q.para86 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(partition(S2l(p.one), p.x))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(partition(structures.Ints2List(p.one), p.x))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0092. Reverse Linked List II/92. Reverse Linked List II.go b/Algorithms/0092. Reverse Linked List II/92. Reverse Linked List II.go index 5b5fcba91..47ada37b1 100644 --- a/Algorithms/0092. Reverse Linked List II/92. Reverse Linked List II.go +++ b/Algorithms/0092. Reverse Linked List II/92. Reverse Linked List II.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0092. Reverse Linked List II/92. Reverse Linked List II_test.go b/Algorithms/0092. Reverse Linked List II/92. Reverse Linked List II_test.go index 52b844a0f..351715019 100644 --- a/Algorithms/0092. Reverse Linked List II/92. Reverse Linked List II_test.go +++ b/Algorithms/0092. Reverse Linked List II/92. Reverse Linked List II_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question92 struct { @@ -62,7 +64,7 @@ func Test_Problem92(t *testing.T) { for _, q := range qs { _, p := q.ans92, q.para92 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(reverseBetween(S2l(p.one), p.m, p.n))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(reverseBetween(structures.Ints2List(p.one), p.m, p.n))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0094. Binary Tree Inorder Traversal/94. Binary Tree Inorder Traversal.go b/Algorithms/0094. Binary Tree Inorder Traversal/94. Binary Tree Inorder Traversal.go index 6965b7ef9..95c6a8a3f 100644 --- a/Algorithms/0094. Binary Tree Inorder Traversal/94. Binary Tree Inorder Traversal.go +++ b/Algorithms/0094. Binary Tree Inorder Traversal/94. Binary Tree Inorder Traversal.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func inorderTraversal(root *TreeNode) []int { var result []int inorder(root, &result) diff --git a/Algorithms/0094. Binary Tree Inorder Traversal/94. Binary Tree Inorder Traversal_test.go b/Algorithms/0094. Binary Tree Inorder Traversal/94. Binary Tree Inorder Traversal_test.go index 5d5b44eb0..8ad80cdd1 100644 --- a/Algorithms/0094. Binary Tree Inorder Traversal/94. Binary Tree Inorder Traversal_test.go +++ b/Algorithms/0094. Binary Tree Inorder Traversal/94. Binary Tree Inorder Traversal_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question94 struct { @@ -37,7 +39,7 @@ func Test_Problem94(t *testing.T) { }, question94{ - para94{[]int{1, NULL, 2, 3}}, + para94{[]int{1, structures.NULL, 2, 3}}, ans94{[]int{1, 2, 3}}, }, } @@ -47,7 +49,7 @@ func Test_Problem94(t *testing.T) { for _, q := range qs { _, p := q.ans94, q.para94 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", inorderTraversal(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0095. Unique Binary Search Trees II/95. Unique Binary Search Trees II.go b/Algorithms/0095. Unique Binary Search Trees II/95. Unique Binary Search Trees II.go index 3d180a62f..d61737dc1 100644 --- a/Algorithms/0095. Unique Binary Search Trees II/95. Unique Binary Search Trees II.go +++ b/Algorithms/0095. Unique Binary Search Trees II/95. Unique Binary Search Trees II.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func generateTrees(n int) []*TreeNode { if n == 0 { return []*TreeNode{} diff --git a/Algorithms/0095. Unique Binary Search Trees II/95. Unique Binary Search Trees II_test.go b/Algorithms/0095. Unique Binary Search Trees II/95. Unique Binary Search Trees II_test.go index c6a6e0418..ab04688aa 100644 --- a/Algorithms/0095. Unique Binary Search Trees II/95. Unique Binary Search Trees II_test.go +++ b/Algorithms/0095. Unique Binary Search Trees II/95. Unique Binary Search Trees II_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question95 struct { @@ -49,7 +51,7 @@ func Test_Problem95(t *testing.T) { fmt.Printf("【input】:%v \n", p) trees := generateTrees(p.one) for _, t := range trees { - fmt.Printf("【output】:%v\n", Tree2Preorder(t)) + fmt.Printf("【output】:%v\n", structures.Tree2Preorder(t)) } } fmt.Printf("\n\n\n") diff --git a/Algorithms/0098. Validate Binary Search Tree/98. Validate Binary Search Tree.go b/Algorithms/0098. Validate Binary Search Tree/98. Validate Binary Search Tree.go index 8e626a68a..801e8ff53 100644 --- a/Algorithms/0098. Validate Binary Search Tree/98. Validate Binary Search Tree.go +++ b/Algorithms/0098. Validate Binary Search Tree/98. Validate Binary Search Tree.go @@ -2,6 +2,13 @@ package leetcode import "math" +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { diff --git a/Algorithms/0098. Validate Binary Search Tree/98. Validate Binary Search Tree_test.go b/Algorithms/0098. Validate Binary Search Tree/98. Validate Binary Search Tree_test.go index f0c54077d..9f567af51 100644 --- a/Algorithms/0098. Validate Binary Search Tree/98. Validate Binary Search Tree_test.go +++ b/Algorithms/0098. Validate Binary Search Tree/98. Validate Binary Search Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question98 struct { @@ -27,7 +29,7 @@ func Test_Problem98(t *testing.T) { qs := []question98{ question98{ - para98{[]int{10, 5, 15, NULL, NULL, 6, 20}}, + para98{[]int{10, 5, 15, structures.NULL, structures.NULL, 6, 20}}, ans98{false}, }, @@ -42,7 +44,7 @@ func Test_Problem98(t *testing.T) { }, question98{ - para98{[]int{5, 1, 4, NULL, NULL, 3, 6}}, + para98{[]int{5, 1, 4, structures.NULL, structures.NULL, 3, 6}}, ans98{false}, }, } @@ -52,7 +54,7 @@ func Test_Problem98(t *testing.T) { for _, q := range qs { _, p := q.ans98, q.para98 fmt.Printf("【input】:%v ", p) - rootOne := Ints2TreeNode(p.one) + rootOne := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", isValidBST(rootOne)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0099. Recover Binary Search Tree/99. Recover Binary Search Tree.go b/Algorithms/0099. Recover Binary Search Tree/99. Recover Binary Search Tree.go index 4b5427b07..57fb92958 100644 --- a/Algorithms/0099. Recover Binary Search Tree/99. Recover Binary Search Tree.go +++ b/Algorithms/0099. Recover Binary Search Tree/99. Recover Binary Search Tree.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func recoverTree(root *TreeNode) { var prev, target1, target2 *TreeNode _, target1, target2 = inOrderTraverse(root, prev, target1, target2) diff --git a/Algorithms/0099. Recover Binary Search Tree/99. Recover Binary Search Tree_test.go b/Algorithms/0099. Recover Binary Search Tree/99. Recover Binary Search Tree_test.go index 472d69e0e..1830affca 100644 --- a/Algorithms/0099. Recover Binary Search Tree/99. Recover Binary Search Tree_test.go +++ b/Algorithms/0099. Recover Binary Search Tree/99. Recover Binary Search Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question99 struct { @@ -27,13 +29,13 @@ func Test_Problem99(t *testing.T) { qs := []question99{ question99{ - para99{[]int{1, 3, NULL, NULL, 2}}, - ans99{[]int{3, 1, NULL, NULL, 2}}, + para99{[]int{1, 3, structures.NULL, structures.NULL, 2}}, + ans99{[]int{3, 1, structures.NULL, structures.NULL, 2}}, }, question99{ - para99{[]int{3, 1, 4, NULL, NULL, 2}}, - ans99{[]int{2, 1, 4, NULL, NULL, 3}}, + para99{[]int{3, 1, 4, structures.NULL, structures.NULL, 2}}, + ans99{[]int{2, 1, 4, structures.NULL, structures.NULL, 3}}, }, } @@ -42,7 +44,7 @@ func Test_Problem99(t *testing.T) { for _, q := range qs { _, p := q.ans99, q.para99 fmt.Printf("【input】:%v ", p) - rootOne := Ints2TreeNode(p.one) + rootOne := structures.Ints2TreeNode(p.one) recoverTree(rootOne) fmt.Printf("【output】:%v \n", p) } diff --git a/Algorithms/0100. Same Tree/100. Same Tree.go b/Algorithms/0100. Same Tree/100. Same Tree.go index ae4056bdb..ab65859b6 100644 --- a/Algorithms/0100. Same Tree/100. Same Tree.go +++ b/Algorithms/0100. Same Tree/100. Same Tree.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func isSameTree(p *TreeNode, q *TreeNode) bool { if p == nil && q == nil { return true diff --git a/Algorithms/0100. Same Tree/100. Same Tree_test.go b/Algorithms/0100. Same Tree/100. Same Tree_test.go index 7da838471..7e727a036 100644 --- a/Algorithms/0100. Same Tree/100. Same Tree_test.go +++ b/Algorithms/0100. Same Tree/100. Same Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question100 struct { @@ -48,7 +50,7 @@ func Test_Problem100(t *testing.T) { }, question100{ - para100{[]int{1, 2}, []int{1, NULL, 2}}, + para100{[]int{1, 2}, []int{1, structures.NULL, 2}}, ans100{false}, }, @@ -63,8 +65,8 @@ func Test_Problem100(t *testing.T) { for _, q := range qs { _, p := q.ans100, q.para100 fmt.Printf("【input】:%v ", p) - rootOne := Ints2TreeNode(p.one) - rootTwo := Ints2TreeNode(p.two) + rootOne := structures.Ints2TreeNode(p.one) + rootTwo := structures.Ints2TreeNode(p.two) fmt.Printf("【output】:%v \n", isSameTree(rootOne, rootTwo)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0101. Symmetric Tree/101. Symmetric Tree.go b/Algorithms/0101. Symmetric Tree/101. Symmetric Tree.go index 8941b092b..cc95bf6ad 100644 --- a/Algorithms/0101. Symmetric Tree/101. Symmetric Tree.go +++ b/Algorithms/0101. Symmetric Tree/101. Symmetric Tree.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,9 +15,33 @@ package leetcode * Right *TreeNode * } */ + func isSymmetric(root *TreeNode) bool { if root == nil { return true } return isSameTree(invertTree(root.Left), root.Right) } + +func isSameTree(p *TreeNode, q *TreeNode) bool { + if p == nil && q == nil { + return true + } else if p != nil && q != nil { + if p.Val != q.Val { + return false + } + return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) + } else { + return false + } +} + +func invertTree(root *TreeNode) *TreeNode { + if root == nil { + return nil + } + invertTree(root.Left) + invertTree(root.Right) + root.Left, root.Right = root.Right, root.Left + return root +} diff --git a/Algorithms/0101. Symmetric Tree/101. Symmetric Tree_test.go b/Algorithms/0101. Symmetric Tree/101. Symmetric Tree_test.go index 99bcf0ba2..db0c69e29 100644 --- a/Algorithms/0101. Symmetric Tree/101. Symmetric Tree_test.go +++ b/Algorithms/0101. Symmetric Tree/101. Symmetric Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question101 struct { @@ -27,12 +29,12 @@ func Test_Problem101(t *testing.T) { qs := []question101{ question101{ - para101{[]int{3, 4, 4, 5, NULL, NULL, 5, 6, NULL, NULL, 6}}, + para101{[]int{3, 4, 4, 5, structures.NULL, structures.NULL, 5, 6, structures.NULL, structures.NULL, 6}}, ans101{true}, }, question101{ - para101{[]int{1, 2, 2, NULL, 3, 3}}, + para101{[]int{1, 2, 2, structures.NULL, 3, 3}}, ans101{true}, }, @@ -57,7 +59,7 @@ func Test_Problem101(t *testing.T) { }, question101{ - para101{[]int{1, 2, 2, NULL, 3, NULL, 3}}, + para101{[]int{1, 2, 2, structures.NULL, 3, structures.NULL, 3}}, ans101{false}, }, } @@ -67,7 +69,7 @@ func Test_Problem101(t *testing.T) { for _, q := range qs { _, p := q.ans101, q.para101 fmt.Printf("【input】:%v ", p) - rootOne := Ints2TreeNode(p.one) + rootOne := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", isSymmetric(rootOne)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0102. Binary Tree Level Order Traversal/102. Binary Tree Level Order Traversal.go b/Algorithms/0102. Binary Tree Level Order Traversal/102. Binary Tree Level Order Traversal.go index 07ab3b1fb..914108c1a 100644 --- a/Algorithms/0102. Binary Tree Level Order Traversal/102. Binary Tree Level Order Traversal.go +++ b/Algorithms/0102. Binary Tree Level Order Traversal/102. Binary Tree Level Order Traversal.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { diff --git a/Algorithms/0102. Binary Tree Level Order Traversal/102. Binary Tree Level Order Traversal_test.go b/Algorithms/0102. Binary Tree Level Order Traversal/102. Binary Tree Level Order Traversal_test.go index 66679c918..cca627c1f 100644 --- a/Algorithms/0102. Binary Tree Level Order Traversal/102. Binary Tree Level Order Traversal_test.go +++ b/Algorithms/0102. Binary Tree Level Order Traversal/102. Binary Tree Level Order Traversal_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question102 struct { @@ -37,7 +39,7 @@ func Test_Problem102(t *testing.T) { }, question102{ - para102{[]int{3, 9, 20, NULL, NULL, 15, 7}}, + para102{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, ans102{[][]int{[]int{3}, []int{9, 20}, []int{15, 7}}}, }, } @@ -47,7 +49,7 @@ func Test_Problem102(t *testing.T) { for _, q := range qs { _, p := q.ans102, q.para102 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", levelOrder(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0103. Binary Tree Zigzag Level Order Traversal/103. Binary Tree Zigzag Level Order Traversal.go b/Algorithms/0103. Binary Tree Zigzag Level Order Traversal/103. Binary Tree Zigzag Level Order Traversal.go index 8d5897d81..30e3d452b 100644 --- a/Algorithms/0103. Binary Tree Zigzag Level Order Traversal/103. Binary Tree Zigzag Level Order Traversal.go +++ b/Algorithms/0103. Binary Tree Zigzag Level Order Traversal/103. Binary Tree Zigzag Level Order Traversal.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func zigzagLevelOrder(root *TreeNode) [][]int { if root == nil { return [][]int{} diff --git a/Algorithms/0103. Binary Tree Zigzag Level Order Traversal/103. Binary Tree Zigzag Level Order Traversal_test.go b/Algorithms/0103. Binary Tree Zigzag Level Order Traversal/103. Binary Tree Zigzag Level Order Traversal_test.go index 7f7bf0591..87cb1cb7a 100644 --- a/Algorithms/0103. Binary Tree Zigzag Level Order Traversal/103. Binary Tree Zigzag Level Order Traversal_test.go +++ b/Algorithms/0103. Binary Tree Zigzag Level Order Traversal/103. Binary Tree Zigzag Level Order Traversal_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question103 struct { @@ -37,12 +39,12 @@ func Test_Problem103(t *testing.T) { }, question103{ - para103{[]int{3, 9, 20, NULL, NULL, 15, 7}}, + para103{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, ans103{[][]int{[]int{3}, []int{9, 20}, []int{15, 7}}}, }, question103{ - para103{[]int{1, 2, 3, 4, NULL, NULL, 5}}, + para103{[]int{1, 2, 3, 4, structures.NULL, structures.NULL, 5}}, ans103{[][]int{[]int{1}, []int{3, 2}, []int{4, 5}}}, }, } @@ -52,7 +54,7 @@ func Test_Problem103(t *testing.T) { for _, q := range qs { _, p := q.ans103, q.para103 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", zigzagLevelOrder(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree.go b/Algorithms/0104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree.go index 73ca1a6e8..7294bc3cb 100644 --- a/Algorithms/0104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree.go +++ b/Algorithms/0104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,9 +15,17 @@ package leetcode * Right *TreeNode * } */ + func maxDepth(root *TreeNode) int { if root == nil { return 0 } return max(maxDepth(root.Left), maxDepth(root.Right)) + 1 } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree_test.go b/Algorithms/0104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree_test.go index 3a79f4006..2c4380c89 100644 --- a/Algorithms/0104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree_test.go +++ b/Algorithms/0104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question104 struct { @@ -32,7 +34,7 @@ func Test_Problem104(t *testing.T) { }, question104{ - para104{[]int{3, 9, 20, NULL, NULL, 15, 7}}, + para104{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, ans104{3}, }, } @@ -42,7 +44,7 @@ func Test_Problem104(t *testing.T) { for _, q := range qs { _, p := q.ans104, q.para104 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", maxDepth(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0105. Construct Binary Tree from Preorder and Inorder Traversal/105. Construct Binary Tree from Preorder and Inorder Traversal.go b/Algorithms/0105. Construct Binary Tree from Preorder and Inorder Traversal/105. Construct Binary Tree from Preorder and Inorder Traversal.go index 983c78d34..b1d2b05fa 100644 --- a/Algorithms/0105. Construct Binary Tree from Preorder and Inorder Traversal/105. Construct Binary Tree from Preorder and Inorder Traversal.go +++ b/Algorithms/0105. Construct Binary Tree from Preorder and Inorder Traversal/105. Construct Binary Tree from Preorder and Inorder Traversal.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func buildTree(preorder []int, inorder []int) *TreeNode { inPos := make(map[int]int) for i := 0; i < len(inorder); i++ { diff --git a/Algorithms/0105. Construct Binary Tree from Preorder and Inorder Traversal/105. Construct Binary Tree from Preorder and Inorder Traversal_test.go b/Algorithms/0105. Construct Binary Tree from Preorder and Inorder Traversal/105. Construct Binary Tree from Preorder and Inorder Traversal_test.go index ac9e32b45..b68fb74e5 100644 --- a/Algorithms/0105. Construct Binary Tree from Preorder and Inorder Traversal/105. Construct Binary Tree from Preorder and Inorder Traversal_test.go +++ b/Algorithms/0105. Construct Binary Tree from Preorder and Inorder Traversal/105. Construct Binary Tree from Preorder and Inorder Traversal_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question105 struct { @@ -29,7 +31,7 @@ func Test_Problem105(t *testing.T) { question105{ para105{[]int{3, 9, 20, 15, 7}, []int{9, 3, 15, 20, 7}}, - ans105{[]int{3, 9, 20, NULL, NULL, 15, 7}}, + ans105{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, }, } @@ -38,7 +40,7 @@ func Test_Problem105(t *testing.T) { for _, q := range qs { _, p := q.ans105, q.para105 fmt.Printf("【input】:%v ", p) - fmt.Printf("【output】:%v \n", Tree2ints(buildTree(p.preorder, p.inorder))) + fmt.Printf("【output】:%v \n", structures.Tree2ints(buildTree(p.preorder, p.inorder))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0106. Construct Binary Tree from Inorder and Postorder Traversal/106. Construct Binary Tree from Inorder and Postorder Traversal.go b/Algorithms/0106. Construct Binary Tree from Inorder and Postorder Traversal/106. Construct Binary Tree from Inorder and Postorder Traversal.go index c4b873b9e..b98a0ec4f 100644 --- a/Algorithms/0106. Construct Binary Tree from Inorder and Postorder Traversal/106. Construct Binary Tree from Inorder and Postorder Traversal.go +++ b/Algorithms/0106. Construct Binary Tree from Inorder and Postorder Traversal/106. Construct Binary Tree from Inorder and Postorder Traversal.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,7 +15,8 @@ package leetcode * Right *TreeNode * } */ -func buildTree106(inorder []int, postorder []int) *TreeNode { + +func buildTree(inorder []int, postorder []int) *TreeNode { inPos := make(map[int]int) for i := 0; i < len(inorder); i++ { inPos[inorder[i]] = i diff --git a/Algorithms/0106. Construct Binary Tree from Inorder and Postorder Traversal/106. Construct Binary Tree from Inorder and Postorder Traversal_test.go b/Algorithms/0106. Construct Binary Tree from Inorder and Postorder Traversal/106. Construct Binary Tree from Inorder and Postorder Traversal_test.go index 2728eebb8..0ff0ca69c 100644 --- a/Algorithms/0106. Construct Binary Tree from Inorder and Postorder Traversal/106. Construct Binary Tree from Inorder and Postorder Traversal_test.go +++ b/Algorithms/0106. Construct Binary Tree from Inorder and Postorder Traversal/106. Construct Binary Tree from Inorder and Postorder Traversal_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question106 struct { @@ -29,7 +31,7 @@ func Test_Problem106(t *testing.T) { question106{ para106{[]int{9, 3, 15, 20, 7}, []int{9, 15, 7, 20, 3}}, - ans106{[]int{3, 9, 20, NULL, NULL, 15, 7}}, + ans106{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, }, } @@ -38,7 +40,7 @@ func Test_Problem106(t *testing.T) { for _, q := range qs { _, p := q.ans106, q.para106 fmt.Printf("【input】:%v ", p) - fmt.Printf("【output】:%v \n", Tree2ints(buildTree106(p.inorder, p.postorder))) + fmt.Printf("【output】:%v \n", structures.Tree2ints(buildTree(p.inorder, p.postorder))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0107. Binary Tree Level Order Traversal II/107. Binary Tree Level Order Traversal II.go b/Algorithms/0107. Binary Tree Level Order Traversal II/107. Binary Tree Level Order Traversal II.go index 682dc1bb7..84a88a7b1 100644 --- a/Algorithms/0107. Binary Tree Level Order Traversal II/107. Binary Tree Level Order Traversal II.go +++ b/Algorithms/0107. Binary Tree Level Order Traversal II/107. Binary Tree Level Order Traversal II.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func levelOrderBottom(root *TreeNode) [][]int { tmp := levelOrder(root) res := [][]int{} @@ -16,3 +24,35 @@ func levelOrderBottom(root *TreeNode) [][]int { } return res } + +func levelOrder(root *TreeNode) [][]int { + if root == nil { + return [][]int{} + } + queue := []*TreeNode{} + queue = append(queue, root) + curNum, nextLevelNum, res, tmp := 1, 0, [][]int{}, []int{} + for len(queue) != 0 { + if curNum > 0 { + node := queue[0] + if node.Left != nil { + queue = append(queue, node.Left) + nextLevelNum++ + } + if node.Right != nil { + queue = append(queue, node.Right) + nextLevelNum++ + } + curNum-- + tmp = append(tmp, node.Val) + queue = queue[1:] + } + if curNum == 0 { + res = append(res, tmp) + curNum = nextLevelNum + nextLevelNum = 0 + tmp = []int{} + } + } + return res +} diff --git a/Algorithms/0107. Binary Tree Level Order Traversal II/107. Binary Tree Level Order Traversal II_test.go b/Algorithms/0107. Binary Tree Level Order Traversal II/107. Binary Tree Level Order Traversal II_test.go index 211cc7f4e..b167f65c7 100644 --- a/Algorithms/0107. Binary Tree Level Order Traversal II/107. Binary Tree Level Order Traversal II_test.go +++ b/Algorithms/0107. Binary Tree Level Order Traversal II/107. Binary Tree Level Order Traversal II_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question107 struct { @@ -37,7 +39,7 @@ func Test_Problem107(t *testing.T) { }, question107{ - para107{[]int{3, 9, 20, NULL, NULL, 15, 7}}, + para107{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, ans107{[][]int{[]int{15, 7}, []int{9, 20}, []int{3}}}, }, } @@ -47,7 +49,7 @@ func Test_Problem107(t *testing.T) { for _, q := range qs { _, p := q.ans107, q.para107 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", levelOrderBottom(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0108. Convert Sorted Array to Binary Search Tree/108. Convert Sorted Array to Binary Search Tree.go b/Algorithms/0108. Convert Sorted Array to Binary Search Tree/108. Convert Sorted Array to Binary Search Tree.go index b5169630d..57e60d7d3 100644 --- a/Algorithms/0108. Convert Sorted Array to Binary Search Tree/108. Convert Sorted Array to Binary Search Tree.go +++ b/Algorithms/0108. Convert Sorted Array to Binary Search Tree/108. Convert Sorted Array to Binary Search Tree.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func sortedArrayToBST(nums []int) *TreeNode { if len(nums) == 0 { return nil diff --git a/Algorithms/0108. Convert Sorted Array to Binary Search Tree/108. Convert Sorted Array to Binary Search Tree_test.go b/Algorithms/0108. Convert Sorted Array to Binary Search Tree/108. Convert Sorted Array to Binary Search Tree_test.go index ed2ca1dd4..0cfdd5a3b 100644 --- a/Algorithms/0108. Convert Sorted Array to Binary Search Tree/108. Convert Sorted Array to Binary Search Tree_test.go +++ b/Algorithms/0108. Convert Sorted Array to Binary Search Tree/108. Convert Sorted Array to Binary Search Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question108 struct { @@ -28,7 +30,7 @@ func Test_Problem108(t *testing.T) { question108{ para108{[]int{-10, -3, 0, 5, 9}}, - ans108{[]int{0, -3, 9, -10, NULL, 5}}, + ans108{[]int{0, -3, 9, -10, structures.NULL, 5}}, }, } @@ -37,7 +39,7 @@ func Test_Problem108(t *testing.T) { for _, q := range qs { _, p := q.ans108, q.para108 arr := []int{} - T2s(sortedArrayToBST(p.one), &arr) + structures.T2s(sortedArrayToBST(p.one), &arr) fmt.Printf("【input】:%v 【output】:%v\n", p, arr) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0109. Convert Sorted List to Binary Search Tree/109. Convert Sorted List to Binary Search Tree.go b/Algorithms/0109. Convert Sorted List to Binary Search Tree/109. Convert Sorted List to Binary Search Tree.go index a5b405738..8edf22873 100644 --- a/Algorithms/0109. Convert Sorted List to Binary Search Tree/109. Convert Sorted List to Binary Search Tree.go +++ b/Algorithms/0109. Convert Sorted List to Binary Search Tree/109. Convert Sorted List to Binary Search Tree.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { @@ -7,6 +14,10 @@ package leetcode * Next *ListNode * } */ + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -16,13 +27,6 @@ package leetcode * } */ -// TreeNode define -type TreeNode struct { - Val int - Left *TreeNode - Right *TreeNode -} - func sortedListToBST(head *ListNode) *TreeNode { if head == nil { return nil diff --git a/Algorithms/0109. Convert Sorted List to Binary Search Tree/109. Convert Sorted List to Binary Search Tree_test.go b/Algorithms/0109. Convert Sorted List to Binary Search Tree/109. Convert Sorted List to Binary Search Tree_test.go index b3ad48c0c..10c362871 100644 --- a/Algorithms/0109. Convert Sorted List to Binary Search Tree/109. Convert Sorted List to Binary Search Tree_test.go +++ b/Algorithms/0109. Convert Sorted List to Binary Search Tree/109. Convert Sorted List to Binary Search Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question109 struct { @@ -28,7 +30,7 @@ func Test_Problem109(t *testing.T) { question109{ para109{[]int{-10, -3, 0, 5, 9}}, - ans109{[]int{0, -10, 5, NULL, -3, NULL, 9}}, + ans109{[]int{0, -10, 5, structures.NULL, -3, structures.NULL, 9}}, }, question109{ @@ -38,7 +40,7 @@ func Test_Problem109(t *testing.T) { question109{ para109{[]int{1, 2}}, - ans109{[]int{2, 1}}, + ans109{[]int{1, 2}}, }, question109{ @@ -52,7 +54,7 @@ func Test_Problem109(t *testing.T) { for _, q := range qs { _, p := q.ans109, q.para109 arr := []int{} - T2s(sortedListToBST(S2l(p.one)), &arr) + structures.T2s(sortedListToBST(structures.Ints2List(p.one)), &arr) fmt.Printf("【input】:%v 【output】:%v\n", p, arr) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0110. Balanced Binary Tree/110. Balanced Binary Tree.go b/Algorithms/0110. Balanced Binary Tree/110. Balanced Binary Tree.go index d7018c329..57b2c7876 100644 --- a/Algorithms/0110. Balanced Binary Tree/110. Balanced Binary Tree.go +++ b/Algorithms/0110. Balanced Binary Tree/110. Balanced Binary Tree.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func isBalanced(root *TreeNode) bool { if root == nil { return true @@ -23,3 +31,17 @@ func depth(root *TreeNode) int { } return max(depth(root.Left), depth(root.Right)) + 1 } + +func abs(a int) int { + if a > 0 { + return a + } + return -a +} + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0110. Balanced Binary Tree/110. Balanced Binary Tree_test.go b/Algorithms/0110. Balanced Binary Tree/110. Balanced Binary Tree_test.go index 9e8b4ae70..785e63137 100644 --- a/Algorithms/0110. Balanced Binary Tree/110. Balanced Binary Tree_test.go +++ b/Algorithms/0110. Balanced Binary Tree/110. Balanced Binary Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question110 struct { @@ -27,12 +29,12 @@ func Test_Problem110(t *testing.T) { qs := []question110{ question110{ - para110{[]int{3, 4, 4, 5, NULL, NULL, 5, 6, NULL, NULL, 6}}, + para110{[]int{3, 4, 4, 5, structures.NULL, structures.NULL, 5, 6, structures.NULL, structures.NULL, 6}}, ans110{false}, }, question110{ - para110{[]int{1, 2, 2, NULL, 3, 3}}, + para110{[]int{1, 2, 2, structures.NULL, 3, 3}}, ans110{true}, }, @@ -57,7 +59,7 @@ func Test_Problem110(t *testing.T) { }, question110{ - para110{[]int{1, 2, 2, NULL, 3, NULL, 3}}, + para110{[]int{1, 2, 2, structures.NULL, 3, structures.NULL, 3}}, ans110{true}, }, } @@ -67,7 +69,7 @@ func Test_Problem110(t *testing.T) { for _, q := range qs { _, p := q.ans110, q.para110 fmt.Printf("【input】:%v ", p) - rootOne := Ints2TreeNode(p.one) + rootOne := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", isBalanced(rootOne)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0111. Minimum Depth of Binary Tree/111. Minimum Depth of Binary Tree.go b/Algorithms/0111. Minimum Depth of Binary Tree/111. Minimum Depth of Binary Tree.go index c3f19bc35..c577ad71c 100644 --- a/Algorithms/0111. Minimum Depth of Binary Tree/111. Minimum Depth of Binary Tree.go +++ b/Algorithms/0111. Minimum Depth of Binary Tree/111. Minimum Depth of Binary Tree.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func minDepth(root *TreeNode) int { if root == nil { return 0 @@ -20,3 +28,10 @@ func minDepth(root *TreeNode) int { } return min(minDepth(root.Left), minDepth(root.Right)) + 1 } + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/0111. Minimum Depth of Binary Tree/111. Minimum Depth of Binary Tree_test.go b/Algorithms/0111. Minimum Depth of Binary Tree/111. Minimum Depth of Binary Tree_test.go index 8d648dc64..8cd759e39 100644 --- a/Algorithms/0111. Minimum Depth of Binary Tree/111. Minimum Depth of Binary Tree_test.go +++ b/Algorithms/0111. Minimum Depth of Binary Tree/111. Minimum Depth of Binary Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question111 struct { @@ -37,7 +39,7 @@ func Test_Problem111(t *testing.T) { }, question111{ - para111{[]int{3, 9, 20, NULL, NULL, 15, 7}}, + para111{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, ans111{2}, }, @@ -52,7 +54,7 @@ func Test_Problem111(t *testing.T) { for _, q := range qs { _, p := q.ans111, q.para111 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", minDepth(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0112. Path Sum/112. Path Sum.go b/Algorithms/0112. Path Sum/112. Path Sum.go index 78b783c47..5ced14fdf 100644 --- a/Algorithms/0112. Path Sum/112. Path Sum.go +++ b/Algorithms/0112. Path Sum/112. Path Sum.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func hasPathSum(root *TreeNode, sum int) bool { if root == nil { return false diff --git a/Algorithms/0112. Path Sum/112. Path Sum_test.go b/Algorithms/0112. Path Sum/112. Path Sum_test.go index ea6618309..7d50ede9a 100644 --- a/Algorithms/0112. Path Sum/112. Path Sum_test.go +++ b/Algorithms/0112. Path Sum/112. Path Sum_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question112 struct { @@ -33,7 +35,7 @@ func Test_Problem112(t *testing.T) { }, question112{ - para112{[]int{5, 4, 8, 11, NULL, 13, 4, 7, 2, NULL, NULL, NULL, 1}, 22}, + para112{[]int{5, 4, 8, 11, structures.NULL, 13, 4, 7, 2, structures.NULL, structures.NULL, structures.NULL, 1}, 22}, ans112{true}, }, } @@ -43,7 +45,7 @@ func Test_Problem112(t *testing.T) { for _, q := range qs { _, p := q.ans112, q.para112 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", hasPathSum(root, p.sum)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0113. Path Sum II/113. Path Sum II.go b/Algorithms/0113. Path Sum II/113. Path Sum II.go index f1846f8d7..0cb5c0443 100644 --- a/Algorithms/0113. Path Sum II/113. Path Sum II.go +++ b/Algorithms/0113. Path Sum II/113. Path Sum II.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { diff --git a/Algorithms/0113. Path Sum II/113. Path Sum II_test.go b/Algorithms/0113. Path Sum II/113. Path Sum II_test.go index bce9f60fd..6de18c28e 100644 --- a/Algorithms/0113. Path Sum II/113. Path Sum II_test.go +++ b/Algorithms/0113. Path Sum II/113. Path Sum II_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question113 struct { @@ -37,7 +39,7 @@ func Test_Problem113(t *testing.T) { }, question113{ - para113{[]int{5, 4, 8, 11, NULL, 13, 4, 7, 2, NULL, NULL, 5, 1}, 22}, + para113{[]int{5, 4, 8, 11, structures.NULL, 13, 4, 7, 2, structures.NULL, structures.NULL, 5, 1}, 22}, ans113{[][]int{[]int{5, 4, 11, 2}, []int{5, 8, 4, 5}}}, }, } @@ -47,7 +49,7 @@ func Test_Problem113(t *testing.T) { for _, q := range qs { _, p := q.ans113, q.para113 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", pathSum(root, p.sum)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0114. Flatten Binary Tree to Linked List/114. Flatten Binary Tree to Linked List.go b/Algorithms/0114. Flatten Binary Tree to Linked List/114. Flatten Binary Tree to Linked List.go index 865988e5a..5fe89309d 100644 --- a/Algorithms/0114. Flatten Binary Tree to Linked List/114. Flatten Binary Tree to Linked List.go +++ b/Algorithms/0114. Flatten Binary Tree to Linked List/114. Flatten Binary Tree to Linked List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -22,6 +29,14 @@ func flatten(root *TreeNode) { return } +func preorder(root *TreeNode, output *[]int) { + if root != nil { + *output = append(*output, root.Val) + preorder(root.Left, output) + preorder(root.Right, output) + } +} + // 解法二 递归 func flatten1(root *TreeNode) { if root == nil || (root.Left == nil && root.Right == nil) { diff --git a/Algorithms/0114. Flatten Binary Tree to Linked List/114. Flatten Binary Tree to Linked List_test.go b/Algorithms/0114. Flatten Binary Tree to Linked List/114. Flatten Binary Tree to Linked List_test.go index 92f2ae6d3..a05d4dbc6 100644 --- a/Algorithms/0114. Flatten Binary Tree to Linked List/114. Flatten Binary Tree to Linked List_test.go +++ b/Algorithms/0114. Flatten Binary Tree to Linked List/114. Flatten Binary Tree to Linked List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question114 struct { @@ -37,9 +39,9 @@ func Test_Problem114(t *testing.T) { for _, q := range qs { _, p := q.ans114, q.para114 fmt.Printf("【input】:%v \n", p) - rootOne := Ints2TreeNode(p.one) + rootOne := structures.Ints2TreeNode(p.one) flatten(rootOne) - fmt.Printf("【output】:%v \n", Tree2Preorder(rootOne)) + fmt.Printf("【output】:%v \n", structures.Tree2Preorder(rootOne)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0120. Triangle/120. Triangle.go b/Algorithms/0120. Triangle/120. Triangle.go index 83a1c47e7..f97b88acd 100644 --- a/Algorithms/0120. Triangle/120. Triangle.go +++ b/Algorithms/0120. Triangle/120. Triangle.go @@ -17,6 +17,13 @@ func minimumTotal(triangle [][]int) int { return triangle[0][0] } +func min(a int, b int) int { + if a > b { + return b + } + return a +} + // 解法二 正常 DP,空间复杂度 O(n) func minimumTotal1(triangle [][]int) int { if len(triangle) == 0 { diff --git a/Algorithms/0121. Best Time to Buy and Sell Stock/121. Best Time to Buy and Sell Stock.go b/Algorithms/0121. Best Time to Buy and Sell Stock/121. Best Time to Buy and Sell Stock.go index d0b2ca17e..012187fd7 100644 --- a/Algorithms/0121. Best Time to Buy and Sell Stock/121. Best Time to Buy and Sell Stock.go +++ b/Algorithms/0121. Best Time to Buy and Sell Stock/121. Best Time to Buy and Sell Stock.go @@ -40,3 +40,10 @@ func maxProfit1(prices []int) int { } return res } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0124. Binary Tree Maximum Path Sum/124. Binary Tree Maximum Path Sum.go b/Algorithms/0124. Binary Tree Maximum Path Sum/124. Binary Tree Maximum Path Sum.go index 186550d90..dc7a75e4b 100644 --- a/Algorithms/0124. Binary Tree Maximum Path Sum/124. Binary Tree Maximum Path Sum.go +++ b/Algorithms/0124. Binary Tree Maximum Path Sum/124. Binary Tree Maximum Path Sum.go @@ -2,6 +2,13 @@ package leetcode import "math" +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -10,6 +17,7 @@ import "math" * Right *TreeNode * } */ + func maxPathSum(root *TreeNode) int { if root == nil { return 0 @@ -30,3 +38,10 @@ func getPathSum(root *TreeNode, maxSum *int) int { *maxSum = max(*maxSum, max(currMax, left+right+root.Val)) return currMax } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0124. Binary Tree Maximum Path Sum/124. Binary Tree Maximum Path Sum_test.go b/Algorithms/0124. Binary Tree Maximum Path Sum/124. Binary Tree Maximum Path Sum_test.go index f196df122..a32dafecc 100644 --- a/Algorithms/0124. Binary Tree Maximum Path Sum/124. Binary Tree Maximum Path Sum_test.go +++ b/Algorithms/0124. Binary Tree Maximum Path Sum/124. Binary Tree Maximum Path Sum_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question124 struct { @@ -42,7 +44,7 @@ func Test_Problem124(t *testing.T) { }, question124{ - para124{[]int{-10, 9, 20, NULL, NULL, 15, 7}}, + para124{[]int{-10, 9, 20, structures.NULL, structures.NULL, 15, 7}}, ans124{42}, }, } @@ -52,7 +54,7 @@ func Test_Problem124(t *testing.T) { for _, q := range qs { _, p := q.ans124, q.para124 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", maxPathSum(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0125. Valid-Palindrome/125. Valid Palindrome.go b/Algorithms/0125. Valid-Palindrome/125. Valid Palindrome.go index dad5d16e6..ce998bd58 100644 --- a/Algorithms/0125. Valid-Palindrome/125. Valid Palindrome.go +++ b/Algorithms/0125. Valid-Palindrome/125. Valid Palindrome.go @@ -1,12 +1,12 @@ package leetcode import ( - "strings" + "strings" ) func isPalindrome(s string) bool { - s = strings.ToLower(s) + s = strings.ToLower(s) i, j := 0, len(s)-1 for i < j { diff --git a/Algorithms/0128. Longest Consecutive Sequence/128. Longest Consecutive Sequence.go b/Algorithms/0128. Longest Consecutive Sequence/128. Longest Consecutive Sequence.go index 34e39771f..a43dc96d6 100644 --- a/Algorithms/0128. Longest Consecutive Sequence/128. Longest Consecutive Sequence.go +++ b/Algorithms/0128. Longest Consecutive Sequence/128. Longest Consecutive Sequence.go @@ -36,6 +36,13 @@ func longestConsecutive(nums []int) int { return res } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + // 解法二 并查集 func longestConsecutive1(nums []int) int { if len(nums) == 0 { diff --git a/Algorithms/0129. Sum Root to Leaf Numbers/129. Sum Root to Leaf Numbers.go b/Algorithms/0129. Sum Root to Leaf Numbers/129. Sum Root to Leaf Numbers.go index 58dbd8710..62fd39bde 100644 --- a/Algorithms/0129. Sum Root to Leaf Numbers/129. Sum Root to Leaf Numbers.go +++ b/Algorithms/0129. Sum Root to Leaf Numbers/129. Sum Root to Leaf Numbers.go @@ -4,6 +4,13 @@ import ( "strconv" ) +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -12,6 +19,7 @@ import ( * Right *TreeNode * } */ + func sumNumbers(root *TreeNode) int { res, nums := 0, binaryTreeNums(root) for _, n := range nums { diff --git a/Algorithms/0129. Sum Root to Leaf Numbers/129. Sum Root to Leaf Numbers_test.go b/Algorithms/0129. Sum Root to Leaf Numbers/129. Sum Root to Leaf Numbers_test.go index 9d68c0f64..b1cd76d4f 100644 --- a/Algorithms/0129. Sum Root to Leaf Numbers/129. Sum Root to Leaf Numbers_test.go +++ b/Algorithms/0129. Sum Root to Leaf Numbers/129. Sum Root to Leaf Numbers_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question129 struct { @@ -47,7 +49,7 @@ func Test_Problem129(t *testing.T) { for _, q := range qs { _, p := q.ans129, q.para129 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", sumNumbers(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0130. Surrounded Regions/130. Surrounded Regions.go b/Algorithms/0130. Surrounded Regions/130. Surrounded Regions.go index 8621a0aee..e7a4628f9 100644 --- a/Algorithms/0130. Surrounded Regions/130. Surrounded Regions.go +++ b/Algorithms/0130. Surrounded Regions/130. Surrounded Regions.go @@ -4,6 +4,13 @@ import ( "github.com/halfrost/LeetCode-Go/template" ) +var dir = [][]int{ + []int{-1, 0}, + []int{0, 1}, + []int{1, 0}, + []int{0, -1}, +} + // 解法一 并查集 func solve(board [][]byte) { if len(board) == 0 { diff --git a/Algorithms/0141. Linked List Cycle/141. Linked List Cycle.go b/Algorithms/0141. Linked List Cycle/141. Linked List Cycle.go index e04ae0484..10eebf0b2 100644 --- a/Algorithms/0141. Linked List Cycle/141. Linked List Cycle.go +++ b/Algorithms/0141. Linked List Cycle/141. Linked List Cycle.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * struct ListNode { diff --git a/Algorithms/0142. Linked List Cycle II/142. Linked List Cycle II.go b/Algorithms/0142. Linked List Cycle II/142. Linked List Cycle II.go index 9d6130302..341d4a0a8 100644 --- a/Algorithms/0142. Linked List Cycle II/142. Linked List Cycle II.go +++ b/Algorithms/0142. Linked List Cycle II/142. Linked List Cycle II.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0143. Reorder List/143. Reorder List.go b/Algorithms/0143. Reorder List/143. Reorder List.go index d48732c9d..d607a8cab 100644 --- a/Algorithms/0143. Reorder List/143. Reorder List.go +++ b/Algorithms/0143. Reorder List/143. Reorder List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0143. Reorder List/143. Reorder List_test.go b/Algorithms/0143. Reorder List/143. Reorder List_test.go index d9a8fb9ac..0e470c040 100644 --- a/Algorithms/0143. Reorder List/143. Reorder List_test.go +++ b/Algorithms/0143. Reorder List/143. Reorder List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question143 struct { @@ -50,7 +52,7 @@ func Test_Problem143(t *testing.T) { for _, q := range qs { _, p := q.ans143, q.para143 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(reorderList(S2l(p.one)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(reorderList(structures.Ints2List(p.one)))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0144. Binary Tree Preorder Traversal/144. Binary Tree Preorder Traversal.go b/Algorithms/0144. Binary Tree Preorder Traversal/144. Binary Tree Preorder Traversal.go index fafa40c4b..816eb1779 100644 --- a/Algorithms/0144. Binary Tree Preorder Traversal/144. Binary Tree Preorder Traversal.go +++ b/Algorithms/0144. Binary Tree Preorder Traversal/144. Binary Tree Preorder Traversal.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { diff --git a/Algorithms/0144. Binary Tree Preorder Traversal/144. Binary Tree Preorder Traversal_test.go b/Algorithms/0144. Binary Tree Preorder Traversal/144. Binary Tree Preorder Traversal_test.go index 1ea66cb25..965129a10 100644 --- a/Algorithms/0144. Binary Tree Preorder Traversal/144. Binary Tree Preorder Traversal_test.go +++ b/Algorithms/0144. Binary Tree Preorder Traversal/144. Binary Tree Preorder Traversal_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question144 struct { @@ -37,7 +39,7 @@ func Test_Problem144(t *testing.T) { }, question144{ - para144{[]int{1, NULL, 2, 3}}, + para144{[]int{1, structures.NULL, 2, 3}}, ans144{[]int{1, 2, 3}}, }, } @@ -47,167 +49,8 @@ func Test_Problem144(t *testing.T) { for _, q := range qs { _, p := q.ans144, q.para144 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", preorderTraversal(root)) } fmt.Printf("\n\n\n") } - -var NULL = -1 << 63 - -// Ints2TreeNode 利用 []int 生成 *TreeNode -func Ints2TreeNode(ints []int) *TreeNode { - n := len(ints) - if n == 0 { - return nil - } - root := &TreeNode{ - Val: ints[0], - } - queue := make([]*TreeNode, 1, n*2) - queue[0] = root - i := 1 - for i < n { - node := queue[0] - queue = queue[1:] - if i < n && ints[i] != NULL { - node.Left = &TreeNode{Val: ints[i]} - queue = append(queue, node.Left) - } - i++ - if i < n && ints[i] != NULL { - node.Right = &TreeNode{Val: ints[i]} - queue = append(queue, node.Right) - } - i++ - } - return root -} - -func indexOf(val int, nums []int) int { - for i, v := range nums { - if v == val { - return i - } - } - - msg := fmt.Sprintf("%d 不存在于 %v 中", val, nums) - panic(msg) -} - -// PreIn2Tree 把 preorder 和 inorder 切片转换成 二叉树 -func PreIn2Tree(pre, in []int) *TreeNode { - if len(pre) != len(in) { - panic("preIn2Tree 中两个切片的长度不相等") - } - if len(in) == 0 { - return nil - } - res := &TreeNode{ - Val: pre[0], - } - if len(in) == 1 { - return res - } - idx := indexOf(res.Val, in) - res.Left = PreIn2Tree(pre[1:idx+1], in[:idx]) - res.Right = PreIn2Tree(pre[idx+1:], in[idx+1:]) - return res -} - -// InPost2Tree 把 inorder 和 postorder 切片转换成 二叉树 -func InPost2Tree(in, post []int) *TreeNode { - if len(post) != len(in) { - panic("inPost2Tree 中两个切片的长度不相等") - } - if len(in) == 0 { - return nil - } - res := &TreeNode{ - Val: post[len(post)-1], - } - if len(in) == 1 { - return res - } - idx := indexOf(res.Val, in) - res.Left = InPost2Tree(in[:idx], post[:idx]) - res.Right = InPost2Tree(in[idx+1:], post[idx:len(post)-1]) - return res -} - -// Tree2Preorder 把 二叉树 转换成 preorder 的切片 -func Tree2Preorder(root *TreeNode) []int { - if root == nil { - return nil - } - if root.Left == nil && root.Right == nil { - return []int{root.Val} - } - res := []int{root.Val} - res = append(res, Tree2Preorder(root.Left)...) - res = append(res, Tree2Preorder(root.Right)...) - return res -} - -// Tree2Inorder 把 二叉树转换成 inorder 的切片 -func Tree2Inorder(root *TreeNode) []int { - if root == nil { - return nil - } - if root.Left == nil && root.Right == nil { - return []int{root.Val} - } - res := Tree2Inorder(root.Left) - res = append(res, root.Val) - res = append(res, Tree2Inorder(root.Right)...) - return res -} - -// Tree2Postorder 把 二叉树 转换成 postorder 的切片 -func Tree2Postorder(root *TreeNode) []int { - if root == nil { - return nil - } - if root.Left == nil && root.Right == nil { - return []int{root.Val} - } - res := Tree2Postorder(root.Left) - res = append(res, Tree2Postorder(root.Right)...) - res = append(res, root.Val) - return res -} - -// Equal return ture if tn == a -func (tn *TreeNode) Equal(a *TreeNode) bool { - if tn == nil && a == nil { - return true - } - if tn == nil || a == nil || tn.Val != a.Val { - return false - } - return tn.Left.Equal(a.Left) && tn.Right.Equal(a.Right) -} - -// Tree2ints 把 *TreeNode 按照行还原成 []int -func Tree2ints(tn *TreeNode) []int { - res := make([]int, 0, 1024) - queue := []*TreeNode{tn} - for len(queue) > 0 { - size := len(queue) - for i := 0; i < size; i++ { - nd := queue[i] - if nd == nil { - res = append(res, NULL) - } else { - res = append(res, nd.Val) - queue = append(queue, nd.Left, nd.Right) - } - } - queue = queue[size:] - } - i := len(res) - for i > 0 && res[i-1] == NULL { - i-- - } - return res[:i] -} diff --git a/Algorithms/0145. Binary Tree Postorder Traversal/145. Binary Tree Postorder Traversal.go b/Algorithms/0145. Binary Tree Postorder Traversal/145. Binary Tree Postorder Traversal.go index bb1844ed5..0923511d5 100644 --- a/Algorithms/0145. Binary Tree Postorder Traversal/145. Binary Tree Postorder Traversal.go +++ b/Algorithms/0145. Binary Tree Postorder Traversal/145. Binary Tree Postorder Traversal.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func postorderTraversal(root *TreeNode) []int { var result []int postorder(root, &result) diff --git a/Algorithms/0145. Binary Tree Postorder Traversal/145. Binary Tree Postorder Traversal_test.go b/Algorithms/0145. Binary Tree Postorder Traversal/145. Binary Tree Postorder Traversal_test.go index 6e786b6d5..f7896413f 100644 --- a/Algorithms/0145. Binary Tree Postorder Traversal/145. Binary Tree Postorder Traversal_test.go +++ b/Algorithms/0145. Binary Tree Postorder Traversal/145. Binary Tree Postorder Traversal_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question145 struct { @@ -37,7 +39,7 @@ func Test_Problem145(t *testing.T) { }, question145{ - para145{[]int{1, NULL, 2, 3}}, + para145{[]int{1, structures.NULL, 2, 3}}, ans145{[]int{1, 2, 3}}, }, } @@ -47,7 +49,7 @@ func Test_Problem145(t *testing.T) { for _, q := range qs { _, p := q.ans145, q.para145 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", postorderTraversal(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0147. Insertion Sort List/147. Insertion Sort List.go b/Algorithms/0147. Insertion Sort List/147. Insertion Sort List.go index 4e98efa46..1b9f13aeb 100644 --- a/Algorithms/0147. Insertion Sort List/147. Insertion Sort List.go +++ b/Algorithms/0147. Insertion Sort List/147. Insertion Sort List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0147. Insertion Sort List/147. Insertion Sort List_test.go b/Algorithms/0147. Insertion Sort List/147. Insertion Sort List_test.go index bddea69a3..d619ae925 100644 --- a/Algorithms/0147. Insertion Sort List/147. Insertion Sort List_test.go +++ b/Algorithms/0147. Insertion Sort List/147. Insertion Sort List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question147 struct { @@ -50,7 +52,7 @@ func Test_Problem147(t *testing.T) { for _, q := range qs { _, p := q.ans147, q.para147 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(insertionSortList(S2l(p.one)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(insertionSortList(structures.Ints2List(p.one)))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0148. Sort List/148. Sort List.go b/Algorithms/0148. Sort List/148. Sort List.go index 049dbb58a..c5132dbb3 100644 --- a/Algorithms/0148. Sort List/148. Sort List.go +++ b/Algorithms/0148. Sort List/148. Sort List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { @@ -55,3 +62,18 @@ func mergeTwoLists148(l1 *ListNode, l2 *ListNode) *ListNode { l2.Next = mergeTwoLists(l1, l2.Next) return l2 } + +func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { + if l1 == nil { + return l2 + } + if l2 == nil { + return l1 + } + if l1.Val < l2.Val { + l1.Next = mergeTwoLists(l1.Next, l2) + return l1 + } + l2.Next = mergeTwoLists(l1, l2.Next) + return l2 +} diff --git a/Algorithms/0148. Sort List/148. Sort List_test.go b/Algorithms/0148. Sort List/148. Sort List_test.go index 871011cb3..d255cde88 100644 --- a/Algorithms/0148. Sort List/148. Sort List_test.go +++ b/Algorithms/0148. Sort List/148. Sort List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question148 struct { @@ -50,7 +52,7 @@ func Test_Problem148(t *testing.T) { for _, q := range qs { _, p := q.ans148, q.para148 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(sortList(S2l(p.one)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(sortList(structures.Ints2List(p.one)))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0152. Maximum Product Subarray/152. Maximum Product Subarray.go b/Algorithms/0152. Maximum Product Subarray/152. Maximum Product Subarray.go index eb2c367ab..4acde4c87 100644 --- a/Algorithms/0152. Maximum Product Subarray/152. Maximum Product Subarray.go +++ b/Algorithms/0152. Maximum Product Subarray/152. Maximum Product Subarray.go @@ -12,3 +12,17 @@ func maxProduct(nums []int) int { } return res } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/0160. Intersection of Two Linked Lists/160. Intersection of Two Linked Lists.go b/Algorithms/0160. Intersection of Two Linked Lists/160. Intersection of Two Linked Lists.go index ac27e70e7..93d68a224 100644 --- a/Algorithms/0160. Intersection of Two Linked Lists/160. Intersection of Two Linked Lists.go +++ b/Algorithms/0160. Intersection of Two Linked Lists/160. Intersection of Two Linked Lists.go @@ -2,6 +2,13 @@ package leetcode import "fmt" +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0160. Intersection of Two Linked Lists/160. Intersection of Two Linked Lists_test.go b/Algorithms/0160. Intersection of Two Linked Lists/160. Intersection of Two Linked Lists_test.go index 95d9a6ecd..e24c710c9 100644 --- a/Algorithms/0160. Intersection of Two Linked Lists/160. Intersection of Two Linked Lists_test.go +++ b/Algorithms/0160. Intersection of Two Linked Lists/160. Intersection of Two Linked Lists_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question160 struct { @@ -62,7 +64,7 @@ func Test_Problem160(t *testing.T) { for _, q := range qs { _, p := q.ans160, q.para160 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(getIntersectionNode(S2l(p.one), S2l(p.another)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(getIntersectionNode(structures.Ints2List(p.one), structures.Ints2List(p.another)))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0164. Maximum Gap/164. Maximum Gap.go b/Algorithms/0164. Maximum Gap/164. Maximum Gap.go index 5462ddb83..bfe40b51a 100644 --- a/Algorithms/0164. Maximum Gap/164. Maximum Gap.go +++ b/Algorithms/0164. Maximum Gap/164. Maximum Gap.go @@ -85,3 +85,10 @@ func maximumGap1(nums []int) int { return maxValue } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0173. Binary Search Tree Iterator/173. Binary Search Tree Iterator.go b/Algorithms/0173. Binary Search Tree Iterator/173. Binary Search Tree Iterator.go index c7986e35e..35f1a69b3 100644 --- a/Algorithms/0173. Binary Search Tree Iterator/173. Binary Search Tree Iterator.go +++ b/Algorithms/0173. Binary Search Tree Iterator/173. Binary Search Tree Iterator.go @@ -2,6 +2,13 @@ package leetcode import "container/heap" +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -28,6 +35,14 @@ func Constructor173(root *TreeNode) BSTIterator { return bs } +func postorder(root *TreeNode, output *[]int) { + if root != nil { + postorder(root.Left, output) + postorder(root.Right, output) + *output = append(*output, root.Val) + } +} + /** @return the next smallest number */ func (this *BSTIterator) Next() int { this.count-- diff --git a/Algorithms/0173. Binary Search Tree Iterator/173. Binary Search Tree Iterator_test.go b/Algorithms/0173. Binary Search Tree Iterator/173. Binary Search Tree Iterator_test.go index 6de0e627a..b9d80ee14 100644 --- a/Algorithms/0173. Binary Search Tree Iterator/173. Binary Search Tree Iterator_test.go +++ b/Algorithms/0173. Binary Search Tree Iterator/173. Binary Search Tree Iterator_test.go @@ -3,11 +3,13 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) func Test_Problem173(t *testing.T) { - root := Ints2TreeNode([]int{9, 7, 15, 3, NULL, NULL, 20}) + root := structures.Ints2TreeNode([]int{9, 7, 15, 3, structures.NULL, structures.NULL, 20}) obj := Constructor173(root) fmt.Printf("obj = %v\n", obj) param1 := obj.Next() diff --git a/Algorithms/0174. Dungeon Game/174. Dungeon Game.go b/Algorithms/0174. Dungeon Game/174. Dungeon Game.go index 0eba7dbc7..db9f0ebe2 100644 --- a/Algorithms/0174. Dungeon Game/174. Dungeon Game.go +++ b/Algorithms/0174. Dungeon Game/174. Dungeon Game.go @@ -27,6 +27,20 @@ func calculateMinimumHP(dungeon [][]int) int { return dp[0][0] } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + +func min(a int, b int) int { + if a > b { + return b + } + return a +} + // 解法二 二分搜索 func calculateMinimumHP1(dungeon [][]int) int { low, high := 1, math.MaxInt64 diff --git a/Algorithms/0198. House Robber/198. House Robber.go b/Algorithms/0198. House Robber/198. House Robber.go index b8a82fca4..9d7b05be6 100644 --- a/Algorithms/0198. House Robber/198. House Robber.go +++ b/Algorithms/0198. House Robber/198. House Robber.go @@ -18,6 +18,13 @@ func rob198(nums []int) int { return dp[n-1] } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + // 解法二 DP 优化辅助空间,把迭代的值保存在 2 个变量中 func rob198_1(nums []int) int { n := len(nums) diff --git a/Algorithms/0199. Binary Tree Right Side View/199. Binary Tree Right Side View.go b/Algorithms/0199. Binary Tree Right Side View/199. Binary Tree Right Side View.go index 70454692b..e30aec0dd 100644 --- a/Algorithms/0199. Binary Tree Right Side View/199. Binary Tree Right Side View.go +++ b/Algorithms/0199. Binary Tree Right Side View/199. Binary Tree Right Side View.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func rightSideView(root *TreeNode) []int { if root == nil { return []int{} diff --git a/Algorithms/0199. Binary Tree Right Side View/199. Binary Tree Right Side View_test.go b/Algorithms/0199. Binary Tree Right Side View/199. Binary Tree Right Side View_test.go index dcb8b2cb1..2e51b9446 100644 --- a/Algorithms/0199. Binary Tree Right Side View/199. Binary Tree Right Side View_test.go +++ b/Algorithms/0199. Binary Tree Right Side View/199. Binary Tree Right Side View_test.go @@ -37,12 +37,12 @@ func Test_Problem199(t *testing.T) { }, question199{ - para199{[]int{3, 9, 20, NULL, NULL, 15, 7}}, + para199{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, ans199{[]int{3, 20, 7}}, }, question199{ - para199{[]int{1, 2, 3, 4, NULL, NULL, 5}}, + para199{[]int{1, 2, 3, 4, structures.NULL, structures.NULL, 5}}, ans199{[]int{1, 3, 5}}, }, } @@ -52,7 +52,7 @@ func Test_Problem199(t *testing.T) { for _, q := range qs { _, p := q.ans199, q.para199 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", rightSideView(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0200. Number of Islands/200. Number of Islands.go b/Algorithms/0200. Number of Islands/200. Number of Islands.go index 94ad94990..dac864a5a 100644 --- a/Algorithms/0200. Number of Islands/200. Number of Islands.go +++ b/Algorithms/0200. Number of Islands/200. Number of Islands.go @@ -1,5 +1,12 @@ package leetcode +var dir = [][]int{ + []int{-1, 0}, + []int{0, 1}, + []int{1, 0}, + []int{0, -1}, +} + func numIslands(grid [][]byte) int { m := len(grid) if m == 0 { @@ -34,3 +41,7 @@ func searchIslands(grid [][]byte, visited *[][]bool, x, y int) { } } } + +func isInBoard(board [][]byte, x, y int) bool { + return x >= 0 && x < len(board) && y >= 0 && y < len(board[0]) +} diff --git a/Algorithms/0203. Remove Linked List Elements/203. Remove Linked List Elements.go b/Algorithms/0203. Remove Linked List Elements/203. Remove Linked List Elements.go index 5b4e74b12..abb2bc9c3 100644 --- a/Algorithms/0203. Remove Linked List Elements/203. Remove Linked List Elements.go +++ b/Algorithms/0203. Remove Linked List Elements/203. Remove Linked List Elements.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0203. Remove Linked List Elements/203. Remove Linked List Elements_test.go b/Algorithms/0203. Remove Linked List Elements/203. Remove Linked List Elements_test.go index 1cdb08961..fe020fb6a 100644 --- a/Algorithms/0203. Remove Linked List Elements/203. Remove Linked List Elements_test.go +++ b/Algorithms/0203. Remove Linked List Elements/203. Remove Linked List Elements_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question203 struct { @@ -72,7 +74,7 @@ func Test_Problem203(t *testing.T) { for _, q := range qs { _, p := q.ans203, q.para203 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(removeElements(S2l(p.one), p.n))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(removeElements(structures.Ints2List(p.one), p.n))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0206. Reverse-Linked-List/206. Reverse Linked List.go b/Algorithms/0206. Reverse-Linked-List/206. Reverse Linked List.go index 3ec9ed2a7..00d2a5682 100644 --- a/Algorithms/0206. Reverse-Linked-List/206. Reverse Linked List.go +++ b/Algorithms/0206. Reverse-Linked-List/206. Reverse Linked List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { @@ -8,12 +15,6 @@ package leetcode * } */ -// ListNode define -type ListNode struct { - Val int - Next *ListNode -} - func reverseList(head *ListNode) *ListNode { var behind *ListNode for head != nil { diff --git a/Algorithms/0206. Reverse-Linked-List/206. Reverse Linked List_test.go b/Algorithms/0206. Reverse-Linked-List/206. Reverse Linked List_test.go index 1ce806f6a..109406a74 100644 --- a/Algorithms/0206. Reverse-Linked-List/206. Reverse Linked List_test.go +++ b/Algorithms/0206. Reverse-Linked-List/206. Reverse Linked List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question206 struct { @@ -36,38 +38,6 @@ func Test_Problem206(t *testing.T) { for _, q := range qs { _, p := q.ans206, q.para206 - fmt.Printf("【input】:%v 【output】:%v\n", p, l2s(reverseList(s2l(p.one)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(reverseList(structures.Ints2List(p.one)))) } } - -// convert *ListNode to []int -func l2s(head *ListNode) []int { - res := []int{} - - for head != nil { - res = append(res, head.Val) - head = head.Next - } - - return res -} - -// convert []int to *ListNode -func s2l(nums []int) *ListNode { - if len(nums) == 0 { - return nil - } - - res := &ListNode{ - Val: nums[0], - } - temp := res - for i := 1; i < len(nums); i++ { - temp.Next = &ListNode{ - Val: nums[i], - } - temp = temp.Next - } - - return res -} diff --git a/Algorithms/0209. Minimum Size Subarray Sum/209. Minimum Size Subarray Sum.go b/Algorithms/0209. Minimum Size Subarray Sum/209. Minimum Size Subarray Sum.go index bee71eb72..3c7a14365 100644 --- a/Algorithms/0209. Minimum Size Subarray Sum/209. Minimum Size Subarray Sum.go +++ b/Algorithms/0209. Minimum Size Subarray Sum/209. Minimum Size Subarray Sum.go @@ -23,3 +23,10 @@ func minSubArrayLen(s int, nums []int) int { } return res } + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/0212. Word Search II/212. Word Search II.go b/Algorithms/0212. Word Search II/212. Word Search II.go index 461e617f1..e8f1da01e 100644 --- a/Algorithms/0212. Word Search II/212. Word Search II.go +++ b/Algorithms/0212. Word Search II/212. Word Search II.go @@ -9,3 +9,48 @@ func findWords(board [][]byte, words []string) []string { } return res } + +// these is 79 solution +var dir = [][]int{ + []int{-1, 0}, + []int{0, 1}, + []int{1, 0}, + []int{0, -1}, +} + +func exist(board [][]byte, word string) bool { + visited := make([][]bool, len(board)) + for i := 0; i < len(visited); i++ { + visited[i] = make([]bool, len(board[0])) + } + for i, v := range board { + for j := range v { + if searchWord(board, visited, word, 0, i, j) { + return true + } + } + } + return false +} + +func isInBoard(board [][]byte, x, y int) bool { + return x >= 0 && x < len(board) && y >= 0 && y < len(board[0]) +} + +func searchWord(board [][]byte, visited [][]bool, word string, index, x, y int) bool { + if index == len(word)-1 { + return board[x][y] == word[index] + } + if board[x][y] == word[index] { + visited[x][y] = true + for i := 0; i < 4; i++ { + nx := x + dir[i][0] + ny := y + dir[i][1] + if isInBoard(board, nx, ny) && !visited[nx][ny] && searchWord(board, visited, word, index+1, nx, ny) { + return true + } + } + visited[x][y] = false + } + return false +} diff --git a/Algorithms/0213. House Robber II/213. House Robber II.go b/Algorithms/0213. House Robber II/213. House Robber II.go index fe1bf32d6..a20a7e105 100644 --- a/Algorithms/0213. House Robber II/213. House Robber II.go +++ b/Algorithms/0213. House Robber II/213. House Robber II.go @@ -25,3 +25,10 @@ func rob213_1(nums []int, start, end int) int { } return curMax } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0215. Kth Largest Element in an Array/215. Kth Largest Element in an Array.go b/Algorithms/0215. Kth Largest Element in an Array/215. Kth Largest Element in an Array.go index 3f7015ff4..20a5672e2 100644 --- a/Algorithms/0215. Kth Largest Element in an Array/215. Kth Largest Element in an Array.go +++ b/Algorithms/0215. Kth Largest Element in an Array/215. Kth Largest Element in an Array.go @@ -29,3 +29,16 @@ func selection(arr []int, l, r, k int) int { return selection(arr, p+1, r, k) } } + +func partition164(a []int, lo, hi int) int { + pivot := a[hi] + i := lo - 1 + for j := lo; j < hi; j++ { + if a[j] < pivot { + i++ + a[j], a[i] = a[i], a[j] + } + } + a[i+1], a[hi] = a[hi], a[i+1] + return i + 1 +} diff --git a/Algorithms/0218. The Skyline Problem/218. The Skyline Problem.go b/Algorithms/0218. The Skyline Problem/218. The Skyline Problem.go index 20178e5e6..b93fa3544 100644 --- a/Algorithms/0218. The Skyline Problem/218. The Skyline Problem.go +++ b/Algorithms/0218. The Skyline Problem/218. The Skyline Problem.go @@ -47,6 +47,13 @@ func discretization218(positions [][]int) (map[int]int, []int) { return posMap, posArray } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + // 解法二 扫描线 Sweep Line,时间复杂度 O(n log n) func getSkyline1(buildings [][]int) [][]int { size := len(buildings) diff --git a/Algorithms/0220. Contains Duplicate III/220. Contains Duplicate III.go b/Algorithms/0220. Contains Duplicate III/220. Contains Duplicate III.go index cd0e9f0dd..2ebd68125 100644 --- a/Algorithms/0220. Contains Duplicate III/220. Contains Duplicate III.go +++ b/Algorithms/0220. Contains Duplicate III/220. Contains Duplicate III.go @@ -34,6 +34,13 @@ func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { return false } +func abs(a int) int { + if a > 0 { + return a + } + return -a +} + type elem struct { val int idx int diff --git a/Algorithms/0222. Count Complete Tree Nodes/222. Count Complete Tree Nodes.go b/Algorithms/0222. Count Complete Tree Nodes/222. Count Complete Tree Nodes.go index 9eee619f4..32c4d4e14 100644 --- a/Algorithms/0222. Count Complete Tree Nodes/222. Count Complete Tree Nodes.go +++ b/Algorithms/0222. Count Complete Tree Nodes/222. Count Complete Tree Nodes.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func countNodes(root *TreeNode) int { if root == nil { return 0 diff --git a/Algorithms/0222. Count Complete Tree Nodes/222. Count Complete Tree Nodes_test.go b/Algorithms/0222. Count Complete Tree Nodes/222. Count Complete Tree Nodes_test.go index 6ce347572..54a3819fe 100644 --- a/Algorithms/0222. Count Complete Tree Nodes/222. Count Complete Tree Nodes_test.go +++ b/Algorithms/0222. Count Complete Tree Nodes/222. Count Complete Tree Nodes_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question222 struct { @@ -52,7 +54,7 @@ func Test_Problem222(t *testing.T) { for _, q := range qs { _, p := q.ans222, q.para222 fmt.Printf("【input】:%v ", p) - rootOne := Ints2TreeNode(p.one) + rootOne := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", countNodes(rootOne)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0223. Rectangle Area/223. Rectangle Area.go b/Algorithms/0223. Rectangle Area/223. Rectangle Area.go index c3d604ccd..8fd9dbdd8 100644 --- a/Algorithms/0223. Rectangle Area/223. Rectangle Area.go +++ b/Algorithms/0223. Rectangle Area/223. Rectangle Area.go @@ -12,3 +12,17 @@ func area(x0, y0, x1, y1 int) int { } return l * h } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/0224. Basic Calculator/224. Basic Calculator.go b/Algorithms/0224. Basic Calculator/224. Basic Calculator.go index 5c1f8d6f8..0804a1b48 100644 --- a/Algorithms/0224. Basic Calculator/224. Basic Calculator.go +++ b/Algorithms/0224. Basic Calculator/224. Basic Calculator.go @@ -111,3 +111,10 @@ func calculateStr(str string) int { fmt.Printf("s = %v nums = %v res = %v\n", string(s), nums, res) return res } + +func isDigital(v byte) bool { + if v >= '0' && v <= '9' { + return true + } + return false +} diff --git a/Algorithms/0226. Invert Binary Tree/226. Invert Binary Tree.go b/Algorithms/0226. Invert Binary Tree/226. Invert Binary Tree.go index e43d8b2cc..bce4e6286 100644 --- a/Algorithms/0226. Invert Binary Tree/226. Invert Binary Tree.go +++ b/Algorithms/0226. Invert Binary Tree/226. Invert Binary Tree.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func invertTree(root *TreeNode) *TreeNode { if root == nil { return nil diff --git a/Algorithms/0226. Invert Binary Tree/226. Invert Binary Tree_test.go b/Algorithms/0226. Invert Binary Tree/226. Invert Binary Tree_test.go index 266c5f35d..9e808b8d7 100644 --- a/Algorithms/0226. Invert Binary Tree/226. Invert Binary Tree_test.go +++ b/Algorithms/0226. Invert Binary Tree/226. Invert Binary Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question226 struct { @@ -47,8 +49,8 @@ func Test_Problem226(t *testing.T) { for _, q := range qs { _, p := q.ans226, q.para226 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) - fmt.Printf("【output】:%v \n", Tree2Preorder(invertTree(root))) + root := structures.Ints2TreeNode(p.one) + fmt.Printf("【output】:%v \n", structures.Tree2Preorder(invertTree(root))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0230. Kth Smallest Element in a BST/230. Kth Smallest Element in a BST.go b/Algorithms/0230. Kth Smallest Element in a BST/230. Kth Smallest Element in a BST.go index f50f8845e..1cef23158 100644 --- a/Algorithms/0230. Kth Smallest Element in a BST/230. Kth Smallest Element in a BST.go +++ b/Algorithms/0230. Kth Smallest Element in a BST/230. Kth Smallest Element in a BST.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func kthSmallest(root *TreeNode, k int) int { res, count := 0, 0 inorder230(root, k, &count, &res) diff --git a/Algorithms/0230. Kth Smallest Element in a BST/230. Kth Smallest Element in a BST_test.go b/Algorithms/0230. Kth Smallest Element in a BST/230. Kth Smallest Element in a BST_test.go index cceea1012..3c5d52fd6 100644 --- a/Algorithms/0230. Kth Smallest Element in a BST/230. Kth Smallest Element in a BST_test.go +++ b/Algorithms/0230. Kth Smallest Element in a BST/230. Kth Smallest Element in a BST_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question230 struct { @@ -33,12 +35,12 @@ func Test_Problem230(t *testing.T) { }, question230{ - para230{[]int{3, 1, 4, NULL, 2}, 1}, + para230{[]int{3, 1, 4, structures.NULL, 2}, 1}, ans230{1}, }, question230{ - para230{[]int{5, 3, 6, 2, 4, NULL, NULL, 1}, 3}, + para230{[]int{5, 3, 6, 2, 4, structures.NULL, structures.NULL, 1}, 3}, ans230{3}, }, } @@ -48,7 +50,7 @@ func Test_Problem230(t *testing.T) { for _, q := range qs { _, p := q.ans230, q.para230 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", kthSmallest(root, p.k)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0234. Palindrome Linked List/234. Palindrome Linked List.go b/Algorithms/0234. Palindrome Linked List/234. Palindrome Linked List.go index b0d06e2de..12cf5e1f9 100644 --- a/Algorithms/0234. Palindrome Linked List/234. Palindrome Linked List.go +++ b/Algorithms/0234. Palindrome Linked List/234. Palindrome Linked List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0234. Palindrome Linked List/234. Palindrome Linked List_test.go b/Algorithms/0234. Palindrome Linked List/234. Palindrome Linked List_test.go index 7995be3bb..74b0592c0 100644 --- a/Algorithms/0234. Palindrome Linked List/234. Palindrome Linked List_test.go +++ b/Algorithms/0234. Palindrome Linked List/234. Palindrome Linked List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question234 struct { @@ -81,7 +83,7 @@ func Test_Problem234(t *testing.T) { for _, q := range qs { _, p := q.ans234, q.para234 - fmt.Printf("【input】:%v 【output】:%v\n", p, isPalindrome234(S2l(p.one))) + fmt.Printf("【input】:%v 【output】:%v\n", p, isPalindrome234(structures.Ints2List(p.one))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0235. Lowest Common Ancestor of a Binary Search Tree/235. Lowest Common Ancestor of a Binary Search Tree.go b/Algorithms/0235. Lowest Common Ancestor of a Binary Search Tree/235. Lowest Common Ancestor of a Binary Search Tree.go index 97a4d8c11..688acd213 100644 --- a/Algorithms/0235. Lowest Common Ancestor of a Binary Search Tree/235. Lowest Common Ancestor of a Binary Search Tree.go +++ b/Algorithms/0235. Lowest Common Ancestor of a Binary Search Tree/235. Lowest Common Ancestor of a Binary Search Tree.go @@ -1,13 +1,21 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** - * Definition for TreeNode. + * Definition for a binary tree node. * type TreeNode struct { * Val int - * Left *ListNode - * Right *ListNode + * Left *TreeNode + * Right *TreeNode * } */ + func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { if p == nil || q == nil || root == nil { return nil diff --git a/Algorithms/0235. Lowest Common Ancestor of a Binary Search Tree/235. Lowest Common Ancestor of a Binary Search Tree_test.go b/Algorithms/0235. Lowest Common Ancestor of a Binary Search Tree/235. Lowest Common Ancestor of a Binary Search Tree_test.go index cb1bc7496..a42c70125 100644 --- a/Algorithms/0235. Lowest Common Ancestor of a Binary Search Tree/235. Lowest Common Ancestor of a Binary Search Tree_test.go +++ b/Algorithms/0235. Lowest Common Ancestor of a Binary Search Tree/235. Lowest Common Ancestor of a Binary Search Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question235 struct { @@ -34,12 +36,12 @@ func Test_Problem235(t *testing.T) { }, question235{ - para235{[]int{6, 2, 8, 0, 4, 7, 9, NULL, NULL, 3, 5}, []int{2}, []int{8}}, + para235{[]int{6, 2, 8, 0, 4, 7, 9, structures.NULL, structures.NULL, 3, 5}, []int{2}, []int{8}}, ans235{[]int{6}}, }, question235{ - para235{[]int{6, 2, 8, 0, 4, 7, 9, NULL, NULL, 3, 5}, []int{2}, []int{4}}, + para235{[]int{6, 2, 8, 0, 4, 7, 9, structures.NULL, structures.NULL, 3, 5}, []int{2}, []int{4}}, ans235{[]int{2}}, }, } @@ -49,9 +51,9 @@ func Test_Problem235(t *testing.T) { for _, q := range qs { _, p := q.ans235, q.para235 fmt.Printf("【input】:%v ", p) - rootOne := Ints2TreeNode(p.one) - rootTwo := Ints2TreeNode(p.two) - rootThr := Ints2TreeNode(p.thr) + rootOne := structures.Ints2TreeNode(p.one) + rootTwo := structures.Ints2TreeNode(p.two) + rootThr := structures.Ints2TreeNode(p.thr) fmt.Printf("【output】:%v \n", lowestCommonAncestor(rootOne, rootTwo, rootThr)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree.go b/Algorithms/0236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree.go index 6f5028d0e..f2c0e8451 100644 --- a/Algorithms/0236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree.go +++ b/Algorithms/0236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree.go @@ -1,13 +1,21 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** - * Definition for TreeNode. + * Definition for a binary tree node. * type TreeNode struct { * Val int - * Left *ListNode - * Right *ListNode + * Left *TreeNode + * Right *TreeNode * } */ + func lowestCommonAncestor236(root, p, q *TreeNode) *TreeNode { if root == nil || root == q || root == p { return root diff --git a/Algorithms/0236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree_test.go b/Algorithms/0236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree_test.go index 5561ef4bf..eae159195 100644 --- a/Algorithms/0236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree_test.go +++ b/Algorithms/0236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question236 struct { @@ -34,22 +36,22 @@ func Test_Problem236(t *testing.T) { }, question236{ - para236{[]int{3, 5, 1, 6, 2, 0, 8, NULL, NULL, 7, 4}, []int{5}, []int{1}}, + para236{[]int{3, 5, 1, 6, 2, 0, 8, structures.NULL, structures.NULL, 7, 4}, []int{5}, []int{1}}, ans236{[]int{3}}, }, question236{ - para236{[]int{3, 5, 1, 6, 2, 0, 8, NULL, NULL, 7, 4}, []int{5}, []int{4}}, + para236{[]int{3, 5, 1, 6, 2, 0, 8, structures.NULL, structures.NULL, 7, 4}, []int{5}, []int{4}}, ans236{[]int{5}}, }, question236{ - para236{[]int{6, 2, 8, 0, 4, 7, 9, NULL, NULL, 3, 5}, []int{2}, []int{8}}, + para236{[]int{6, 2, 8, 0, 4, 7, 9, structures.NULL, structures.NULL, 3, 5}, []int{2}, []int{8}}, ans236{[]int{6}}, }, question236{ - para236{[]int{6, 2, 8, 0, 4, 7, 9, NULL, NULL, 3, 5}, []int{2}, []int{4}}, + para236{[]int{6, 2, 8, 0, 4, 7, 9, structures.NULL, structures.NULL, 3, 5}, []int{2}, []int{4}}, ans236{[]int{2}}, }, } @@ -59,9 +61,9 @@ func Test_Problem236(t *testing.T) { for _, q := range qs { _, p := q.ans236, q.para236 fmt.Printf("【input】:%v ", p) - rootOne := Ints2TreeNode(p.one) - rootTwo := Ints2TreeNode(p.two) - rootThr := Ints2TreeNode(p.thr) + rootOne := structures.Ints2TreeNode(p.one) + rootTwo := structures.Ints2TreeNode(p.two) + rootThr := structures.Ints2TreeNode(p.thr) fmt.Printf("【output】:%v \n", lowestCommonAncestor236(rootOne, rootTwo, rootThr)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0237. Delete Node in a Linked List/237. Delete Node in a Linked List.go b/Algorithms/0237. Delete Node in a Linked List/237. Delete Node in a Linked List.go index ba5356b7f..78186ba93 100644 --- a/Algorithms/0237. Delete Node in a Linked List/237. Delete Node in a Linked List.go +++ b/Algorithms/0237. Delete Node in a Linked List/237. Delete Node in a Linked List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0237. Delete Node in a Linked List/237. Delete Node in a Linked List_test.go b/Algorithms/0237. Delete Node in a Linked List/237. Delete Node in a Linked List_test.go index 727011f03..81c370e8d 100644 --- a/Algorithms/0237. Delete Node in a Linked List/237. Delete Node in a Linked List_test.go +++ b/Algorithms/0237. Delete Node in a Linked List/237. Delete Node in a Linked List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question237 struct { @@ -67,7 +69,25 @@ func Test_Problem237(t *testing.T) { for _, q := range qs { _, p := q.ans237, q.para237 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(removeElements(S2l(p.one), p.n))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(removeElements(structures.Ints2List(p.one), p.n))) } fmt.Printf("\n\n\n") } + +func removeElements(head *ListNode, val int) *ListNode { + if head == nil { + return head + } + newHead := &ListNode{Val: 0, Next: head} + pre := newHead + cur := head + for cur != nil { + if cur.Val == val { + pre.Next = cur.Next + } else { + pre = cur + } + cur = cur.Next + } + return newHead.Next +} diff --git a/Algorithms/0257. Binary Tree Paths/257. Binary Tree Paths.go b/Algorithms/0257. Binary Tree Paths/257. Binary Tree Paths.go index 0ea32c52f..4640cf7f6 100644 --- a/Algorithms/0257. Binary Tree Paths/257. Binary Tree Paths.go +++ b/Algorithms/0257. Binary Tree Paths/257. Binary Tree Paths.go @@ -4,6 +4,13 @@ import ( "strconv" ) +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -12,6 +19,7 @@ import ( * Right *TreeNode * } */ + func binaryTreePaths(root *TreeNode) []string { if root == nil { return []string{} diff --git a/Algorithms/0257. Binary Tree Paths/257. Binary Tree Paths_test.go b/Algorithms/0257. Binary Tree Paths/257. Binary Tree Paths_test.go index 194d1427e..cba57aaf1 100644 --- a/Algorithms/0257. Binary Tree Paths/257. Binary Tree Paths_test.go +++ b/Algorithms/0257. Binary Tree Paths/257. Binary Tree Paths_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question257 struct { @@ -32,7 +34,7 @@ func Test_Problem257(t *testing.T) { }, question257{ - para257{[]int{1, 2, 3, NULL, 5, NULL, NULL}}, + para257{[]int{1, 2, 3, structures.NULL, 5, structures.NULL, structures.NULL}}, ans257{[]string{"1->2->5", "1->3"}}, }, @@ -47,7 +49,7 @@ func Test_Problem257(t *testing.T) { for _, q := range qs { _, p := q.ans257, q.para257 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", binaryTreePaths(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0274. H-Index/274. H-Index.go b/Algorithms/0274. H-Index/274. H-Index.go index 9d59c9dbc..b26d4d823 100644 --- a/Algorithms/0274. H-Index/274. H-Index.go +++ b/Algorithms/0274. H-Index/274. H-Index.go @@ -34,3 +34,25 @@ func hIndex1(citations []int) int { } return hIndex } + +func quickSort164(a []int, lo, hi int) { + if lo >= hi { + return + } + p := partition164(a, lo, hi) + quickSort164(a, lo, p-1) + quickSort164(a, p+1, hi) +} + +func partition164(a []int, lo, hi int) int { + pivot := a[hi] + i := lo - 1 + for j := lo; j < hi; j++ { + if a[j] < pivot { + i++ + a[j], a[i] = a[i], a[j] + } + } + a[i+1], a[hi] = a[hi], a[i+1] + return i + 1 +} diff --git a/Algorithms/0300. Longest Increasing Subsequence/300. Longest Increasing Subsequence.go b/Algorithms/0300. Longest Increasing Subsequence/300. Longest Increasing Subsequence.go index a0e1eb32b..a658bab8b 100644 --- a/Algorithms/0300. Longest Increasing Subsequence/300. Longest Increasing Subsequence.go +++ b/Algorithms/0300. Longest Increasing Subsequence/300. Longest Increasing Subsequence.go @@ -18,6 +18,13 @@ func lengthOfLIS(nums []int) int { return res } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + // 解法二 O(n log n) DP func lengthOfLIS1(nums []int) int { dp := []int{} diff --git a/Algorithms/0306. Additive Number/306. Additive Number.go b/Algorithms/0306. Additive Number/306. Additive Number.go index 9aac8ee56..1489b05c8 100644 --- a/Algorithms/0306. Additive Number/306. Additive Number.go +++ b/Algorithms/0306. Additive Number/306. Additive Number.go @@ -28,6 +28,13 @@ func isAdditiveNumber(num string) bool { return false } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + //Propagate for rest of the string func recursiveCheck(num string, x1 int, x2 int, left int) bool { if left == len(num) { diff --git a/Algorithms/0307. Range Sum Query - Mutable/307. Range Sum Query - Mutable.go b/Algorithms/0307. Range Sum Query - Mutable/307. Range Sum Query - Mutable.go index 5b84a304f..884b0c8bb 100644 --- a/Algorithms/0307. Range Sum Query - Mutable/307. Range Sum Query - Mutable.go +++ b/Algorithms/0307. Range Sum Query - Mutable/307. Range Sum Query - Mutable.go @@ -4,6 +4,11 @@ import ( "github.com/halfrost/LeetCode-Go/template" ) +// NumArray define +type NumArray struct { + st *template.SegmentTree +} + // Constructor307 define func Constructor307(nums []int) NumArray { st := template.SegmentTree{} diff --git a/Algorithms/0307. Range Sum Query - Mutable/307. Range Sum Query - Mutable_test.go b/Algorithms/0307. Range Sum Query - Mutable/307. Range Sum Query - Mutable_test.go index 6ea6ccd1f..1f8d8f88e 100644 --- a/Algorithms/0307. Range Sum Query - Mutable/307. Range Sum Query - Mutable_test.go +++ b/Algorithms/0307. Range Sum Query - Mutable/307. Range Sum Query - Mutable_test.go @@ -13,3 +13,8 @@ func Test_Problem307(t *testing.T) { fmt.Printf("obj = %v\n", obj) fmt.Printf("SumRange(0,2) = %v\n", obj.SumRange(0, 2)) } + +// SumRange define +func (ma *NumArray) SumRange(i int, j int) int { + return ma.st.Query(i, j) +} diff --git a/Algorithms/0309. Best Time to Buy and Sell Stock with Cooldown/309. Best Time to Buy and Sell Stock with Cooldown.go b/Algorithms/0309. Best Time to Buy and Sell Stock with Cooldown/309. Best Time to Buy and Sell Stock with Cooldown.go index 5e2c02f4d..f6bd86d00 100644 --- a/Algorithms/0309. Best Time to Buy and Sell Stock with Cooldown/309. Best Time to Buy and Sell Stock with Cooldown.go +++ b/Algorithms/0309. Best Time to Buy and Sell Stock with Cooldown/309. Best Time to Buy and Sell Stock with Cooldown.go @@ -23,6 +23,13 @@ func maxProfit309(prices []int) int { return sell[len(sell)-1] } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + // 解法二 优化辅助空间的 DP func maxProfit309_1(prices []int) int { if len(prices) <= 1 { diff --git a/Algorithms/0322. Coin Change/322. Coin Change.go b/Algorithms/0322. Coin Change/322. Coin Change.go index c9c7e1b89..a8fdcb994 100644 --- a/Algorithms/0322. Coin Change/322. Coin Change.go +++ b/Algorithms/0322. Coin Change/322. Coin Change.go @@ -18,3 +18,10 @@ func coinChange(coins []int, amount int) int { } return dp[amount] } + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/0328. Odd Even Linked List/328. Odd Even Linked List.go b/Algorithms/0328. Odd Even Linked List/328. Odd Even Linked List.go index 4f771cc6b..5281610c0 100644 --- a/Algorithms/0328. Odd Even Linked List/328. Odd Even Linked List.go +++ b/Algorithms/0328. Odd Even Linked List/328. Odd Even Linked List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0328. Odd Even Linked List/328. Odd Even Linked List_test.go b/Algorithms/0328. Odd Even Linked List/328. Odd Even Linked List_test.go index d66cedcfa..5e3547ac9 100644 --- a/Algorithms/0328. Odd Even Linked List/328. Odd Even Linked List_test.go +++ b/Algorithms/0328. Odd Even Linked List/328. Odd Even Linked List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question328 struct { @@ -66,7 +68,7 @@ func Test_Problem328(t *testing.T) { for _, q := range qs { _, p := q.ans328, q.para328 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(oddEvenList(S2l(p.one)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(oddEvenList(structures.Ints2List(p.one)))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0329. Longest Increasing Path in a Matrix/329. Longest Increasing Path in a Matrix.go b/Algorithms/0329. Longest Increasing Path in a Matrix/329. Longest Increasing Path in a Matrix.go index 791df53b3..2e43102f2 100644 --- a/Algorithms/0329. Longest Increasing Path in a Matrix/329. Longest Increasing Path in a Matrix.go +++ b/Algorithms/0329. Longest Increasing Path in a Matrix/329. Longest Increasing Path in a Matrix.go @@ -4,6 +4,13 @@ import ( "math" ) +var dir = [][]int{ + []int{-1, 0}, + []int{0, 1}, + []int{1, 0}, + []int{0, -1}, +} + func longestIncreasingPath(matrix [][]int) int { cache, res := make([][]int, len(matrix)), 0 for i := 0; i < len(cache); i++ { @@ -18,6 +25,13 @@ func longestIncreasingPath(matrix [][]int) int { return res } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + func isInIntBoard(board [][]int, x, y int) bool { return x >= 0 && x < len(board) && y >= 0 && y < len(board[0]) } diff --git a/Algorithms/0343. Integer Break/343. Integer Break.go b/Algorithms/0343. Integer Break/343. Integer Break.go index 0a30e3438..fea86ccfe 100644 --- a/Algorithms/0343. Integer Break/343. Integer Break.go +++ b/Algorithms/0343. Integer Break/343. Integer Break.go @@ -11,3 +11,10 @@ func integerBreak(n int) int { } return dp[n] } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0385. Mini Parser/385. Mini Parser.go b/Algorithms/0385. Mini Parser/385. Mini Parser.go index ffbd1818d..fee25200b 100644 --- a/Algorithms/0385. Mini Parser/385. Mini Parser.go +++ b/Algorithms/0385. Mini Parser/385. Mini Parser.go @@ -115,3 +115,10 @@ func deserialize(s string) *NestedInteger { } return cur } + +func isDigital(v byte) bool { + if v >= '0' && v <= '9' { + return true + } + return false +} diff --git a/Algorithms/0404. Sum of Left Leaves/404. Sum of Left Leaves.go b/Algorithms/0404. Sum of Left Leaves/404. Sum of Left Leaves.go index a089b1417..6e0cdf5eb 100644 --- a/Algorithms/0404. Sum of Left Leaves/404. Sum of Left Leaves.go +++ b/Algorithms/0404. Sum of Left Leaves/404. Sum of Left Leaves.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func sumOfLeftLeaves(root *TreeNode) int { if root == nil { return 0 diff --git a/Algorithms/0404. Sum of Left Leaves/404. Sum of Left Leaves_test.go b/Algorithms/0404. Sum of Left Leaves/404. Sum of Left Leaves_test.go index c593abe7b..bdfd80bce 100644 --- a/Algorithms/0404. Sum of Left Leaves/404. Sum of Left Leaves_test.go +++ b/Algorithms/0404. Sum of Left Leaves/404. Sum of Left Leaves_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question404 struct { @@ -32,7 +34,7 @@ func Test_Problem404(t *testing.T) { }, question404{ - para404{[]int{3, 9, 20, NULL, NULL, 15, 7}}, + para404{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, ans404{24}, }, } @@ -42,7 +44,7 @@ func Test_Problem404(t *testing.T) { for _, q := range qs { _, p := q.ans404, q.para404 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", sumOfLeftLeaves(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0424. Longest Repeating Character Replacement/424. Longest Repeating Character Replacement.go b/Algorithms/0424. Longest Repeating Character Replacement/424. Longest Repeating Character Replacement.go index 874b00280..7c1a0b40b 100644 --- a/Algorithms/0424. Longest Repeating Character Replacement/424. Longest Repeating Character Replacement.go +++ b/Algorithms/0424. Longest Repeating Character Replacement/424. Longest Repeating Character Replacement.go @@ -13,3 +13,10 @@ func characterReplacement(s string, k int) int { } return res } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0433. Minimum Genetic Mutation/433. Minimum Genetic Mutation.go b/Algorithms/0433. Minimum Genetic Mutation/433. Minimum Genetic Mutation.go index e4e9cf4f9..9c1b5d2b8 100644 --- a/Algorithms/0433. Minimum Genetic Mutation/433. Minimum Genetic Mutation.go +++ b/Algorithms/0433. Minimum Genetic Mutation/433. Minimum Genetic Mutation.go @@ -24,6 +24,18 @@ func minMutation(start string, end string, bank []string) int { return -1 } +func getWordMap(wordList []string, beginWord string) map[string]int { + wordMap := make(map[string]int) + for i, word := range wordList { + if _, ok := wordMap[word]; !ok { + if word != beginWord { + wordMap[word] = i + } + } + } + return wordMap +} + func getCandidates433(word string) []string { var res []string for i := 0; i < 26; i++ { diff --git a/Algorithms/0435. Non-overlapping Intervals/435. Non-overlapping Intervals.go b/Algorithms/0435. Non-overlapping Intervals/435. Non-overlapping Intervals.go index 6a3fcc4dd..5abdb20d9 100644 --- a/Algorithms/0435. Non-overlapping Intervals/435. Non-overlapping Intervals.go +++ b/Algorithms/0435. Non-overlapping Intervals/435. Non-overlapping Intervals.go @@ -27,6 +27,13 @@ func eraseOverlapIntervals(intervals [][]int) int { return len(intervals) - res } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + // Intervals define type Intervals [][]int diff --git a/Algorithms/0436. Find Right Interval/436. Find Right Interval.go b/Algorithms/0436. Find Right Interval/436. Find Right Interval.go index 775837d3f..101730533 100644 --- a/Algorithms/0436. Find Right Interval/436. Find Right Interval.go +++ b/Algorithms/0436. Find Right Interval/436. Find Right Interval.go @@ -1,6 +1,13 @@ package leetcode -import "sort" +import ( + "sort" + + "github.com/halfrost/LeetCode-Go/structures" +) + +// Interval define +type Interval = structures.Interval // 解法一 利用系统函数 sort + 二分搜索 func findRightInterval(intervals [][]int) []int { @@ -45,7 +52,7 @@ func findRightInterval1(intervals [][]int) []int { intervalsList = append(intervalsList, Interval{Start: v[0], End: v[1]}) intervalMap[Interval{Start: v[0], End: v[1]}] = k } - quickSort(intervalsList, 0, len(intervalsList)-1) + structures.QuickSort(intervalsList, 0, len(intervalsList)-1) for _, v := range intervals { tmp := searchFirstGreaterInterval(intervalsList, v[1]) if tmp > 0 { diff --git a/Algorithms/0437. Path Sum III/437. Path Sum III.go b/Algorithms/0437. Path Sum III/437. Path Sum III.go index 29adc8e7d..96e208ec6 100644 --- a/Algorithms/0437. Path Sum III/437. Path Sum III.go +++ b/Algorithms/0437. Path Sum III/437. Path Sum III.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func pathSumIII(root *TreeNode, sum int) int { if root == nil { return 0 diff --git a/Algorithms/0437. Path Sum III/437. Path Sum III_test.go b/Algorithms/0437. Path Sum III/437. Path Sum III_test.go index 71a727d70..4b19a6711 100644 --- a/Algorithms/0437. Path Sum III/437. Path Sum III_test.go +++ b/Algorithms/0437. Path Sum III/437. Path Sum III_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question437 struct { @@ -32,7 +34,7 @@ func Test_Problem437(t *testing.T) { }, question437{ - para437{[]int{10, 5, -3, 3, 2, NULL, 11, 3, -2, NULL, 1}, 8}, + para437{[]int{10, 5, -3, 3, 2, structures.NULL, 11, 3, -2, structures.NULL, 1}, 8}, ans437{3}, }, } @@ -42,7 +44,7 @@ func Test_Problem437(t *testing.T) { for _, q := range qs { _, p := q.ans437, q.para437 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", pathSumIII(root, p.sum)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0445. Add Two Numbers II/445. Add Two Numbers II.go b/Algorithms/0445. Add Two Numbers II/445. Add Two Numbers II.go index 68822c1cd..3211805ad 100644 --- a/Algorithms/0445. Add Two Numbers II/445. Add Two Numbers II.go +++ b/Algorithms/0445. Add Two Numbers II/445. Add Two Numbers II.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0445. Add Two Numbers II/445. Add Two Numbers II_test.go b/Algorithms/0445. Add Two Numbers II/445. Add Two Numbers II_test.go index 2c1bd3526..b2df6e744 100644 --- a/Algorithms/0445. Add Two Numbers II/445. Add Two Numbers II_test.go +++ b/Algorithms/0445. Add Two Numbers II/445. Add Two Numbers II_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question445 struct { @@ -73,7 +75,7 @@ func Test_Problem445(t *testing.T) { for _, q := range qs { _, p := q.ans445, q.para445 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(addTwoNumbers445(S2l(p.one), S2l(p.another)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(addTwoNumbers445(structures.Ints2List(p.one), structures.Ints2List(p.another)))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0474. Ones and Zeroes/474. Ones and Zeroes.go b/Algorithms/0474. Ones and Zeroes/474. Ones and Zeroes.go index 6f7cf049c..aa36966d8 100644 --- a/Algorithms/0474. Ones and Zeroes/474. Ones and Zeroes.go +++ b/Algorithms/0474. Ones and Zeroes/474. Ones and Zeroes.go @@ -21,3 +21,10 @@ func findMaxForm(strs []string, m int, n int) int { } return dp[m][n] } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0475. Heaters/475. Heaters.go b/Algorithms/0475. Heaters/475. Heaters.go index 381a89a9d..382b097e1 100644 --- a/Algorithms/0475. Heaters/475. Heaters.go +++ b/Algorithms/0475. Heaters/475. Heaters.go @@ -61,3 +61,24 @@ func findRadius1(houses []int, heaters []int) int { } return res } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} + +func min(a int, b int) int { + if a > b { + return b + } + return a +} + +func abs(a int) int { + if a > 0 { + return a + } + return -a +} diff --git a/Algorithms/0477. Total Hamming Distance/477. Total Hamming Distance.go b/Algorithms/0477. Total Hamming Distance/477. Total Hamming Distance.go index bb85707dd..d05a3c3e3 100644 --- a/Algorithms/0477. Total Hamming Distance/477. Total Hamming Distance.go +++ b/Algorithms/0477. Total Hamming Distance/477. Total Hamming Distance.go @@ -22,3 +22,11 @@ func totalHammingDistance1(nums []int) int { } return res } + +func hammingDistance(x int, y int) int { + distance := 0 + for xor := x ^ y; xor != 0; xor &= (xor - 1) { + distance++ + } + return distance +} diff --git a/Algorithms/0508. Most Frequent Subtree Sum/508. Most Frequent Subtree Sum.go b/Algorithms/0508. Most Frequent Subtree Sum/508. Most Frequent Subtree Sum.go index 93767e024..c35b7f7b3 100644 --- a/Algorithms/0508. Most Frequent Subtree Sum/508. Most Frequent Subtree Sum.go +++ b/Algorithms/0508. Most Frequent Subtree Sum/508. Most Frequent Subtree Sum.go @@ -4,6 +4,13 @@ import ( "sort" ) +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { diff --git a/Algorithms/0508. Most Frequent Subtree Sum/508. Most Frequent Subtree Sum_test.go b/Algorithms/0508. Most Frequent Subtree Sum/508. Most Frequent Subtree Sum_test.go index a37302fb9..abb636677 100644 --- a/Algorithms/0508. Most Frequent Subtree Sum/508. Most Frequent Subtree Sum_test.go +++ b/Algorithms/0508. Most Frequent Subtree Sum/508. Most Frequent Subtree Sum_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question508 struct { @@ -57,7 +59,7 @@ func Test_Problem508(t *testing.T) { for _, q := range qs { _, p := q.ans508, q.para508 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", findFrequentTreeSum(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0513. Find Bottom Left Tree Value/513. Find Bottom Left Tree Value.go b/Algorithms/0513. Find Bottom Left Tree Value/513. Find Bottom Left Tree Value.go index db34e2f6f..b4ca1ebc2 100644 --- a/Algorithms/0513. Find Bottom Left Tree Value/513. Find Bottom Left Tree Value.go +++ b/Algorithms/0513. Find Bottom Left Tree Value/513. Find Bottom Left Tree Value.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { diff --git a/Algorithms/0513. Find Bottom Left Tree Value/513. Find Bottom Left Tree Value_test.go b/Algorithms/0513. Find Bottom Left Tree Value/513. Find Bottom Left Tree Value_test.go index c0b678362..815a42ff8 100644 --- a/Algorithms/0513. Find Bottom Left Tree Value/513. Find Bottom Left Tree Value_test.go +++ b/Algorithms/0513. Find Bottom Left Tree Value/513. Find Bottom Left Tree Value_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question513 struct { @@ -37,12 +39,12 @@ func Test_Problem513(t *testing.T) { }, question513{ - para513{[]int{3, 9, 20, NULL, NULL, 15, 7}}, + para513{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, ans513{15}, }, question513{ - para513{[]int{1, 2, 3, 4, NULL, NULL, 5}}, + para513{[]int{1, 2, 3, 4, structures.NULL, structures.NULL, 5}}, ans513{4}, }, } @@ -52,7 +54,7 @@ func Test_Problem513(t *testing.T) { for _, q := range qs { _, p := q.ans513, q.para513 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", findBottomLeftValue(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0515. Find Largest Value in Each Tree Row/515. Find Largest Value in Each Tree Row.go b/Algorithms/0515. Find Largest Value in Each Tree Row/515. Find Largest Value in Each Tree Row.go index 812adbe82..042956e8c 100644 --- a/Algorithms/0515. Find Largest Value in Each Tree Row/515. Find Largest Value in Each Tree Row.go +++ b/Algorithms/0515. Find Largest Value in Each Tree Row/515. Find Largest Value in Each Tree Row.go @@ -5,6 +5,13 @@ import ( "sort" ) +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -25,6 +32,39 @@ func largestValues(root *TreeNode) []int { return res } +// this is 102 solution +func levelOrder(root *TreeNode) [][]int { + if root == nil { + return [][]int{} + } + queue := []*TreeNode{} + queue = append(queue, root) + curNum, nextLevelNum, res, tmp := 1, 0, [][]int{}, []int{} + for len(queue) != 0 { + if curNum > 0 { + node := queue[0] + if node.Left != nil { + queue = append(queue, node.Left) + nextLevelNum++ + } + if node.Right != nil { + queue = append(queue, node.Right) + nextLevelNum++ + } + curNum-- + tmp = append(tmp, node.Val) + queue = queue[1:] + } + if curNum == 0 { + res = append(res, tmp) + curNum = nextLevelNum + nextLevelNum = 0 + tmp = []int{} + } + } + return res +} + // 解法二 层序遍历二叉树,遍历过程中不断更新最大值 func largestValues1(root *TreeNode) []int { if root == nil { diff --git a/Algorithms/0515. Find Largest Value in Each Tree Row/515. Find Largest Value in Each Tree Row_test.go b/Algorithms/0515. Find Largest Value in Each Tree Row/515. Find Largest Value in Each Tree Row_test.go index 5811b3edc..2c5a9c1c4 100644 --- a/Algorithms/0515. Find Largest Value in Each Tree Row/515. Find Largest Value in Each Tree Row_test.go +++ b/Algorithms/0515. Find Largest Value in Each Tree Row/515. Find Largest Value in Each Tree Row_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question515 struct { @@ -37,12 +39,12 @@ func Test_Problem515(t *testing.T) { }, question515{ - para515{[]int{1, 3, 2, 5, 3, NULL, 9}}, + para515{[]int{1, 3, 2, 5, 3, structures.NULL, 9}}, ans515{[]int{1, 3, 9}}, }, question515{ - para515{[]int{3, 9, 20, NULL, NULL, 15, 7}}, + para515{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, ans515{[]int{3, 20, 15}}, }, } @@ -52,7 +54,7 @@ func Test_Problem515(t *testing.T) { for _, q := range qs { _, p := q.ans515, q.para515 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", largestValues(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0541. Reverse String II/541. Reverse String II.go b/Algorithms/0541. Reverse String II/541. Reverse String II.go index fe300150f..ff00b877b 100644 --- a/Algorithms/0541. Reverse String II/541. Reverse String II.go +++ b/Algorithms/0541. Reverse String II/541. Reverse String II.go @@ -15,3 +15,14 @@ func reverseStr(s string, k int) string { } return s } + +func revers(s string) string { + bytes := []byte(s) + i, j := 0, len(bytes)-1 + for i < j { + bytes[i], bytes[j] = bytes[j], bytes[i] + i++ + j-- + } + return string(bytes) +} diff --git a/Algorithms/0542. 01 Matrix/542. 01 Matrix.go b/Algorithms/0542. 01 Matrix/542. 01 Matrix.go index 6ee0cf10b..b2f358459 100644 --- a/Algorithms/0542. 01 Matrix/542. 01 Matrix.go +++ b/Algorithms/0542. 01 Matrix/542. 01 Matrix.go @@ -140,3 +140,10 @@ func updateMatrixDP(matrix [][]int) [][]int { } return matrix } + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/0563. Binary Tree Tilt/563. Binary Tree Tilt.go b/Algorithms/0563. Binary Tree Tilt/563. Binary Tree Tilt.go index d443e3c18..74aa00974 100644 --- a/Algorithms/0563. Binary Tree Tilt/563. Binary Tree Tilt.go +++ b/Algorithms/0563. Binary Tree Tilt/563. Binary Tree Tilt.go @@ -2,6 +2,13 @@ package leetcode import "math" +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -10,6 +17,7 @@ import "math" * Right *TreeNode * } */ + func findTilt(root *TreeNode) int { if root == nil { return 0 diff --git a/Algorithms/0563. Binary Tree Tilt/563. Binary Tree Tilt_test.go b/Algorithms/0563. Binary Tree Tilt/563. Binary Tree Tilt_test.go index 77444cb74..380838863 100644 --- a/Algorithms/0563. Binary Tree Tilt/563. Binary Tree Tilt_test.go +++ b/Algorithms/0563. Binary Tree Tilt/563. Binary Tree Tilt_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question563 struct { @@ -37,17 +39,17 @@ func Test_Problem563(t *testing.T) { }, question563{ - para563{[]int{3, 9, 20, NULL, NULL, 15, 7}}, + para563{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, ans563{41}, }, question563{ - para563{[]int{1, 2, 3, 4, NULL, NULL, 5}}, + para563{[]int{1, 2, 3, 4, structures.NULL, structures.NULL, 5}}, ans563{11}, }, question563{ - para563{[]int{1, 2, 3, 4, NULL, 5}}, + para563{[]int{1, 2, 3, 4, structures.NULL, 5}}, ans563{11}, }, } @@ -57,7 +59,7 @@ func Test_Problem563(t *testing.T) { for _, q := range qs { _, p := q.ans563, q.para563 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", findTilt(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0572. Subtree of Another Tree/572. Subtree of Another Tree.go b/Algorithms/0572. Subtree of Another Tree/572. Subtree of Another Tree.go index de74977ba..6ec9bf468 100644 --- a/Algorithms/0572. Subtree of Another Tree/572. Subtree of Another Tree.go +++ b/Algorithms/0572. Subtree of Another Tree/572. Subtree of Another Tree.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func isSubtree(s *TreeNode, t *TreeNode) bool { if isSameTree(s, t) { return true @@ -20,3 +28,17 @@ func isSubtree(s *TreeNode, t *TreeNode) bool { } return false } + +// this is 100 solution +func isSameTree(p *TreeNode, q *TreeNode) bool { + if p == nil && q == nil { + return true + } else if p != nil && q != nil { + if p.Val != q.Val { + return false + } + return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) + } else { + return false + } +} diff --git a/Algorithms/0572. Subtree of Another Tree/572. Subtree of Another Tree_test.go b/Algorithms/0572. Subtree of Another Tree/572. Subtree of Another Tree_test.go index b65303702..ec44000fc 100644 --- a/Algorithms/0572. Subtree of Another Tree/572. Subtree of Another Tree_test.go +++ b/Algorithms/0572. Subtree of Another Tree/572. Subtree of Another Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question572 struct { @@ -29,7 +31,7 @@ func Test_Problem572(t *testing.T) { question572{ para572{[]int{}, []int{}}, - ans572{false}, + ans572{true}, }, question572{ @@ -43,7 +45,7 @@ func Test_Problem572(t *testing.T) { }, question572{ - para572{[]int{1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, 2}, []int{1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, 2}}, + para572{[]int{1, structures.NULL, 1, structures.NULL, 1, structures.NULL, 1, structures.NULL, 1, structures.NULL, 1, structures.NULL, 1, structures.NULL, 1, structures.NULL, 1, structures.NULL, 1, structures.NULL, 1, 2}, []int{1, structures.NULL, 1, structures.NULL, 1, structures.NULL, 1, structures.NULL, 1, structures.NULL, 1, 2}}, ans572{true}, }, } @@ -53,8 +55,8 @@ func Test_Problem572(t *testing.T) { for _, q := range qs { _, p := q.ans572, q.para572 fmt.Printf("【input】:%v ", p) - roots := Ints2TreeNode(p.s) - roott := Ints2TreeNode(p.t) + roots := structures.Ints2TreeNode(p.s) + roott := structures.Ints2TreeNode(p.t) fmt.Printf("【output】:%v \n", isSubtree(roots, roott)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0628. Maximum Product of Three Numbers/628. Maximum Product of Three Numbers.go b/Algorithms/0628. Maximum Product of Three Numbers/628. Maximum Product of Three Numbers.go index 41b7a78ac..1a481bff8 100644 --- a/Algorithms/0628. Maximum Product of Three Numbers/628. Maximum Product of Three Numbers.go +++ b/Algorithms/0628. Maximum Product of Three Numbers/628. Maximum Product of Three Numbers.go @@ -23,6 +23,13 @@ func maximumProduct(nums []int) int { return max(nums[0]*nums[1]*nums[len(nums)-1], nums[len(nums)-1]*nums[len(nums)-2]*nums[len(nums)-3]) } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + // 解法二 模拟,时间复杂度 O(n) func maximumProduct1(nums []int) int { n1, n2, n3 := -1<<63, -1<<63, -1<<63 diff --git a/Algorithms/0637. Average of Levels in Binary Tree/637. Average of Levels in Binary Tree.go b/Algorithms/0637. Average of Levels in Binary Tree/637. Average of Levels in Binary Tree.go index 89f783b97..372186991 100644 --- a/Algorithms/0637. Average of Levels in Binary Tree/637. Average of Levels in Binary Tree.go +++ b/Algorithms/0637. Average of Levels in Binary Tree/637. Average of Levels in Binary Tree.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func averageOfLevels(root *TreeNode) []float64 { if root == nil { return []float64{0} diff --git a/Algorithms/0637. Average of Levels in Binary Tree/637. Average of Levels in Binary Tree_test.go b/Algorithms/0637. Average of Levels in Binary Tree/637. Average of Levels in Binary Tree_test.go index 50b94f35e..da4bfb214 100644 --- a/Algorithms/0637. Average of Levels in Binary Tree/637. Average of Levels in Binary Tree_test.go +++ b/Algorithms/0637. Average of Levels in Binary Tree/637. Average of Levels in Binary Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question637 struct { @@ -37,7 +39,7 @@ func Test_Problem637(t *testing.T) { }, question637{ - para637{[]int{3, 9, 20, NULL, NULL, 15, 7}}, + para637{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, ans637{[][]int{[]int{3}, []int{9, 20}, []int{15, 7}}}, }, } @@ -47,7 +49,7 @@ func Test_Problem637(t *testing.T) { for _, q := range qs { _, p := q.ans637, q.para637 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", averageOfLevels(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0648. Replace Words/648. Replace Words.go b/Algorithms/0648. Replace Words/648. Replace Words.go index 037452083..d742af98f 100644 --- a/Algorithms/0648. Replace Words/648. Replace Words.go +++ b/Algorithms/0648. Replace Words/648. Replace Words.go @@ -62,3 +62,41 @@ func replaceWords1(dict []string, sentence string) string { } return strings.Join(result, " ") } + +type Trie struct { + isWord bool + children map[rune]*Trie +} + +/** Initialize your data structure here. */ +func Constructor208() Trie { + return Trie{isWord: false, children: make(map[rune]*Trie)} +} + +/** Inserts a word into the trie. */ +func (this *Trie) Insert(word string) { + parent := this + for _, ch := range word { + if child, ok := parent.children[ch]; ok { + parent = child + } else { + newChild := &Trie{children: make(map[rune]*Trie)} + parent.children[ch] = newChild + parent = newChild + } + } + parent.isWord = true +} + +/** Returns if the word is in the trie. */ +func (this *Trie) Search(word string) bool { + parent := this + for _, ch := range word { + if child, ok := parent.children[ch]; ok { + parent = child + continue + } + return false + } + return parent.isWord +} diff --git a/Algorithms/0653. Two Sum IV - Input is a BST/653. Two Sum IV - Input is a BST.go b/Algorithms/0653. Two Sum IV - Input is a BST/653. Two Sum IV - Input is a BST.go index 8a98bbbf6..03fbc0037 100644 --- a/Algorithms/0653. Two Sum IV - Input is a BST/653. Two Sum IV - Input is a BST.go +++ b/Algorithms/0653. Two Sum IV - Input is a BST/653. Two Sum IV - Input is a BST.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func findTarget(root *TreeNode, k int) bool { m := make(map[int]int, 0) return findTargetDFS(root, k, m) diff --git a/Algorithms/0653. Two Sum IV - Input is a BST/653. Two Sum IV - Input is a BST_test.go b/Algorithms/0653. Two Sum IV - Input is a BST/653. Two Sum IV - Input is a BST_test.go index 84b1b7cfa..dd82f53da 100644 --- a/Algorithms/0653. Two Sum IV - Input is a BST/653. Two Sum IV - Input is a BST_test.go +++ b/Algorithms/0653. Two Sum IV - Input is a BST/653. Two Sum IV - Input is a BST_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question653 struct { @@ -33,17 +35,17 @@ func Test_Problem653(t *testing.T) { }, question653{ - para653{[]int{3, 9, 20, NULL, NULL, 15, 7}, 29}, + para653{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}, 29}, ans653{true}, }, question653{ - para653{[]int{1, 2, 3, 4, NULL, NULL, 5}, 9}, + para653{[]int{1, 2, 3, 4, structures.NULL, structures.NULL, 5}, 9}, ans653{true}, }, question653{ - para653{[]int{1, 2, 3, 4, NULL, 5}, 4}, + para653{[]int{1, 2, 3, 4, structures.NULL, 5}, 4}, ans653{true}, }, } @@ -53,7 +55,7 @@ func Test_Problem653(t *testing.T) { for _, q := range qs { _, p := q.ans653, q.para653 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", findTarget(root, p.k)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0662. Maximum Width of Binary Tree/662. Maximum Width of Binary Tree.go b/Algorithms/0662. Maximum Width of Binary Tree/662. Maximum Width of Binary Tree.go index 17f552a22..0c973abd0 100644 --- a/Algorithms/0662. Maximum Width of Binary Tree/662. Maximum Width of Binary Tree.go +++ b/Algorithms/0662. Maximum Width of Binary Tree/662. Maximum Width of Binary Tree.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func widthOfBinaryTree(root *TreeNode) int { if root == nil { return 0 @@ -61,3 +69,10 @@ func widthOfBinaryTree(root *TreeNode) int { } return res } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0662. Maximum Width of Binary Tree/662. Maximum Width of Binary Tree_test.go b/Algorithms/0662. Maximum Width of Binary Tree/662. Maximum Width of Binary Tree_test.go index 8f4e3d617..a4b49d0a2 100644 --- a/Algorithms/0662. Maximum Width of Binary Tree/662. Maximum Width of Binary Tree_test.go +++ b/Algorithms/0662. Maximum Width of Binary Tree/662. Maximum Width of Binary Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question662 struct { @@ -27,12 +29,12 @@ func Test_Problem662(t *testing.T) { qs := []question662{ question662{ - para662{[]int{1, 1, 1, 1, 1, 1, 1, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, 2, 2, 2, 2, 2, 2, 2, NULL, 2, NULL, NULL, 2, NULL, 2}}, + para662{[]int{1, 1, 1, 1, 1, 1, 1, structures.NULL, structures.NULL, structures.NULL, 1, structures.NULL, structures.NULL, structures.NULL, structures.NULL, 2, 2, 2, 2, 2, 2, 2, structures.NULL, 2, structures.NULL, structures.NULL, 2, structures.NULL, 2}}, ans662{8}, }, question662{ - para662{[]int{1, 1, 1, 1, NULL, NULL, 1, 1, NULL, NULL, 1}}, + para662{[]int{1, 1, 1, 1, structures.NULL, structures.NULL, 1, 1, structures.NULL, structures.NULL, 1}}, ans662{8}, }, @@ -47,7 +49,7 @@ func Test_Problem662(t *testing.T) { }, question662{ - para662{[]int{1, 3, 2, 5, 3, NULL, 9}}, + para662{[]int{1, 3, 2, 5, 3, structures.NULL, 9}}, ans662{4}, }, } @@ -57,7 +59,7 @@ func Test_Problem662(t *testing.T) { for _, q := range qs { _, p := q.ans662, q.para662 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", widthOfBinaryTree(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0699. Falling Squares/699. Falling Squares.go b/Algorithms/0699. Falling Squares/699. Falling Squares.go index f87785157..bc6dc5daf 100644 --- a/Algorithms/0699. Falling Squares/699. Falling Squares.go +++ b/Algorithms/0699. Falling Squares/699. Falling Squares.go @@ -36,3 +36,10 @@ func discretization(positions [][]int) map[int]int { } return posMap } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0707. Design Linked List/707. Design Linked List_test.go b/Algorithms/0707. Design Linked List/707. Design Linked List_test.go index 790da6eab..4b61e11fd 100644 --- a/Algorithms/0707. Design Linked List/707. Design Linked List_test.go +++ b/Algorithms/0707. Design Linked List/707. Design Linked List_test.go @@ -7,52 +7,52 @@ import ( func Test_Problem707(t *testing.T) { obj := Constructor() - fmt.Printf("obj = %v\n", ML2s(&obj)) + fmt.Printf("obj = %v\n", MList2Ints(&obj)) param1 := obj.Get(1) - fmt.Printf("param_1 = %v obj = %v\n", param1, ML2s(&obj)) + fmt.Printf("param_1 = %v obj = %v\n", param1, MList2Ints(&obj)) obj.AddAtHead(38) - fmt.Printf("obj = %v\n", ML2s(&obj)) + fmt.Printf("obj = %v\n", MList2Ints(&obj)) obj.AddAtHead(45) - fmt.Printf("obj = %v\n", ML2s(&obj)) + fmt.Printf("obj = %v\n", MList2Ints(&obj)) obj.DeleteAtIndex(2) - fmt.Printf("obj = %v\n", ML2s(&obj)) + fmt.Printf("obj = %v\n", MList2Ints(&obj)) obj.AddAtIndex(1, 24) - fmt.Printf("obj = %v\n", ML2s(&obj)) + fmt.Printf("obj = %v\n", MList2Ints(&obj)) obj.AddAtTail(36) - fmt.Printf("obj = %v\n", ML2s(&obj)) + fmt.Printf("obj = %v\n", MList2Ints(&obj)) obj.AddAtIndex(3, 72) obj.AddAtTail(76) - fmt.Printf("obj = %v\n", ML2s(&obj)) + fmt.Printf("obj = %v\n", MList2Ints(&obj)) obj.AddAtHead(7) - fmt.Printf("obj = %v\n", ML2s(&obj)) + fmt.Printf("obj = %v\n", MList2Ints(&obj)) obj.AddAtHead(36) - fmt.Printf("obj = %v\n", ML2s(&obj)) + fmt.Printf("obj = %v\n", MList2Ints(&obj)) obj.AddAtHead(34) - fmt.Printf("obj = %v\n", ML2s(&obj)) + fmt.Printf("obj = %v\n", MList2Ints(&obj)) obj.AddAtTail(91) - fmt.Printf("obj = %v\n", ML2s(&obj)) + fmt.Printf("obj = %v\n", MList2Ints(&obj)) fmt.Printf("\n\n\n") obj1 := Constructor() - fmt.Printf("obj1 = %v\n", ML2s(&obj1)) + fmt.Printf("obj1 = %v\n", MList2Ints(&obj1)) param2 := obj1.Get(0) - fmt.Printf("param_2 = %v obj1 = %v\n", param2, ML2s(&obj1)) + fmt.Printf("param_2 = %v obj1 = %v\n", param2, MList2Ints(&obj1)) obj1.AddAtIndex(1, 2) - fmt.Printf("obj1 = %v\n", ML2s(&obj1)) + fmt.Printf("obj1 = %v\n", MList2Ints(&obj1)) param2 = obj1.Get(0) - fmt.Printf("param_2 = %v obj1 = %v\n", param2, ML2s(&obj1)) + fmt.Printf("param_2 = %v obj1 = %v\n", param2, MList2Ints(&obj1)) param2 = obj1.Get(1) - fmt.Printf("param_2 = %v obj1 = %v\n", param2, ML2s(&obj1)) + fmt.Printf("param_2 = %v obj1 = %v\n", param2, MList2Ints(&obj1)) obj1.AddAtIndex(0, 1) - fmt.Printf("obj1 = %v\n", ML2s(&obj1)) + fmt.Printf("obj1 = %v\n", MList2Ints(&obj1)) param2 = obj1.Get(0) - fmt.Printf("param_1 = %v obj1 = %v\n", param2, ML2s(&obj1)) + fmt.Printf("param_1 = %v obj1 = %v\n", param2, MList2Ints(&obj1)) param2 = obj1.Get(1) - fmt.Printf("param_2 = %v obj1 = %v\n", param2, ML2s(&obj1)) + fmt.Printf("param_2 = %v obj1 = %v\n", param2, MList2Ints(&obj1)) } -func ML2s(head *MyLinkedList) []int { +func MList2Ints(head *MyLinkedList) []int { res := []int{} for head != nil { diff --git a/Algorithms/0714. Best Time to Buy and Sell Stock with Transaction Fee/714. Best Time to Buy and Sell Stock with Transaction Fee.go b/Algorithms/0714. Best Time to Buy and Sell Stock with Transaction Fee/714. Best Time to Buy and Sell Stock with Transaction Fee.go index 2a2847593..702c2d7a1 100644 --- a/Algorithms/0714. Best Time to Buy and Sell Stock with Transaction Fee/714. Best Time to Buy and Sell Stock with Transaction Fee.go +++ b/Algorithms/0714. Best Time to Buy and Sell Stock with Transaction Fee/714. Best Time to Buy and Sell Stock with Transaction Fee.go @@ -21,6 +21,13 @@ func maxProfit714(prices []int, fee int) int { return sell[len(sell)-1] } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + // 解法二 优化辅助空间的 DP func maxProfit714_1(prices []int, fee int) int { sell, buy := 0, -prices[0] diff --git a/Algorithms/0714. Best Time to Buy and Sell Stock with Transaction Fee/714. Best Time to Buy and Sell Stock with Transaction Fee_test.go b/Algorithms/0714. Best Time to Buy and Sell Stock with Transaction Fee/714. Best Time to Buy and Sell Stock with Transaction Fee_test.go index d4eb73e5b..3bcdce3ab 100644 --- a/Algorithms/0714. Best Time to Buy and Sell Stock with Transaction Fee/714. Best Time to Buy and Sell Stock with Transaction Fee_test.go +++ b/Algorithms/0714. Best Time to Buy and Sell Stock with Transaction Fee/714. Best Time to Buy and Sell Stock with Transaction Fee_test.go @@ -34,7 +34,7 @@ func Test_Problem714(t *testing.T) { question714{ para714{[]int{7, 1, 5, 3, 6, 4}, 0}, - ans714{5}, + ans714{7}, }, question714{ diff --git a/Algorithms/0718. Maximum Length of Repeated Subarray/718. Maximum Length of Repeated Subarray.go b/Algorithms/0718. Maximum Length of Repeated Subarray/718. Maximum Length of Repeated Subarray.go index 3eec755f2..8a74cc9ae 100644 --- a/Algorithms/0718. Maximum Length of Repeated Subarray/718. Maximum Length of Repeated Subarray.go +++ b/Algorithms/0718. Maximum Length of Repeated Subarray/718. Maximum Length of Repeated Subarray.go @@ -16,6 +16,13 @@ func findLength(A []int, B []int) int { return low } +func min(a int, b int) int { + if a > b { + return b + } + return a +} + func hashSlice(arr []int, length int) []int { // hash 数组里面记录 arr 比 length 长出去部分的 hash 值 hash, pl, h := make([]int, len(arr)-length+1), 1, 0 diff --git a/Algorithms/0725. Split Linked List in Parts/725. Split Linked List in Parts.go b/Algorithms/0725. Split Linked List in Parts/725. Split Linked List in Parts.go index 34b803aa3..167b4ae9b 100644 --- a/Algorithms/0725. Split Linked List in Parts/725. Split Linked List in Parts.go +++ b/Algorithms/0725. Split Linked List in Parts/725. Split Linked List in Parts.go @@ -2,6 +2,13 @@ package leetcode import "fmt" +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { @@ -62,3 +69,13 @@ func splitListToParts(root *ListNode, k int) []*ListNode { } return res } + +func getLength(l *ListNode) int { + count := 0 + cur := l + for cur != nil { + count++ + cur = cur.Next + } + return count +} diff --git a/Algorithms/0725. Split Linked List in Parts/725. Split Linked List in Parts_test.go b/Algorithms/0725. Split Linked List in Parts/725. Split Linked List in Parts_test.go index 433086fa5..e9fab2ac5 100644 --- a/Algorithms/0725. Split Linked List in Parts/725. Split Linked List in Parts_test.go +++ b/Algorithms/0725. Split Linked List in Parts/725. Split Linked List in Parts_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question725 struct { @@ -77,9 +79,9 @@ func Test_Problem725(t *testing.T) { for _, q := range qs { _, p := q.ans725, q.para725 - res := splitListToParts(S2l(p.one), p.n) + res := splitListToParts(structures.Ints2List(p.one), p.n) for _, value := range res { - fmt.Printf("【input】:%v length:%v 【output】:%v\n", p, len(res), L2s(value)) + fmt.Printf("【input】:%v length:%v 【output】:%v\n", p, len(res), structures.List2Ints(value)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0725. Split Linked List in Parts/README.md b/Algorithms/0725. Split Linked List in Parts/README.md index 74112a288..b535964f2 100644 --- a/Algorithms/0725. Split Linked List in Parts/README.md +++ b/Algorithms/0725. Split Linked List in Parts/README.md @@ -22,7 +22,7 @@ Explanation: The input and each element of the output are ListNodes, not arrays. For example, the input root has root.val = 1, root.next.val = 2, \root.next.next.val = 3, and root.next.next.next = null. The first element output[0] has output[0].val = 1, output[0].next = null. -The last element output[4] is null, but it's string representation as a ListNode is []. +The last element output[4] is NULL, but it's string representation as a ListNode is []. ``` Example 2: diff --git a/Algorithms/0733. Flood Fill/733. Flood Fill.go b/Algorithms/0733. Flood Fill/733. Flood Fill.go index 6782310bc..38bd3bef8 100644 --- a/Algorithms/0733. Flood Fill/733. Flood Fill.go +++ b/Algorithms/0733. Flood Fill/733. Flood Fill.go @@ -1,5 +1,12 @@ package leetcode +var dir = [][]int{ + []int{-1, 0}, + []int{0, 1}, + []int{1, 0}, + []int{0, -1}, +} + func floodFill(image [][]int, sr int, sc int, newColor int) [][]int { color := image[sr][sc] if newColor == color { diff --git a/Algorithms/0746. Min Cost Climbing Stairs/746. Min Cost Climbing Stairs.go b/Algorithms/0746. Min Cost Climbing Stairs/746. Min Cost Climbing Stairs.go index ac475d2f4..7d68e9c6c 100644 --- a/Algorithms/0746. Min Cost Climbing Stairs/746. Min Cost Climbing Stairs.go +++ b/Algorithms/0746. Min Cost Climbing Stairs/746. Min Cost Climbing Stairs.go @@ -10,6 +10,13 @@ func minCostClimbingStairs(cost []int) int { return min(dp[len(cost)-2], dp[len(cost)-1]) } +func min(a int, b int) int { + if a > b { + return b + } + return a +} + // 解法二 DP 优化辅助空间 func minCostClimbingStairs1(cost []int) int { var cur, last int diff --git a/Algorithms/0784. Letter Case Permutation/784. Letter Case Permutation.go b/Algorithms/0784. Letter Case Permutation/784. Letter Case Permutation.go index 5708cbb9d..7f2b13ca1 100644 --- a/Algorithms/0784. Letter Case Permutation/784. Letter Case Permutation.go +++ b/Algorithms/0784. Letter Case Permutation/784. Letter Case Permutation.go @@ -22,6 +22,13 @@ func letterCasePermutation(S string) []string { return res } +func isLowerLetter(v byte) bool { + if v >= 'a' && v <= 'z' { + return true + } + return false +} + func findLetterCasePermutation(s string, pos []int, target, index int, c []int, res *[]string) { if len(c) == target { b := []byte(s) diff --git a/Algorithms/0793. Preimage Size of Factorial Zeroes Function/793. Preimage Size of Factorial Zeroes Function.go b/Algorithms/0793. Preimage Size of Factorial Zeroes Function/793. Preimage Size of Factorial Zeroes Function.go index 3c95a93e3..cc8e88ecd 100644 --- a/Algorithms/0793. Preimage Size of Factorial Zeroes Function/793. Preimage Size of Factorial Zeroes Function.go +++ b/Algorithms/0793. Preimage Size of Factorial Zeroes Function/793. Preimage Size of Factorial Zeroes Function.go @@ -17,6 +17,13 @@ func preimageSizeFZF(K int) int { return 0 } +func trailingZeroes(n int) int { + if n/5 == 0 { + return 0 + } + return n/5 + trailingZeroes(n/5) +} + // 解法二 数学方法 func preimageSizeFZF1(K int) int { base := 0 diff --git a/Algorithms/0803. Bricks Falling When Hit/803. Bricks Falling When Hit.go b/Algorithms/0803. Bricks Falling When Hit/803. Bricks Falling When Hit.go index 48eaa7bc5..6ec4f44f6 100644 --- a/Algorithms/0803. Bricks Falling When Hit/803. Bricks Falling When Hit.go +++ b/Algorithms/0803. Bricks Falling When Hit/803. Bricks Falling When Hit.go @@ -4,6 +4,13 @@ import ( "github.com/halfrost/LeetCode-Go/template" ) +var dir = [][]int{ + []int{-1, 0}, + []int{0, 1}, + []int{1, 0}, + []int{0, -1}, +} + func hitBricks(grid [][]int, hits [][]int) []int { if len(hits) == 0 { return []int{} diff --git a/Algorithms/0817. Linked List Components/817. Linked List Components.go b/Algorithms/0817. Linked List Components/817. Linked List Components.go index b4b726193..66592ae2c 100644 --- a/Algorithms/0817. Linked List Components/817. Linked List Components.go +++ b/Algorithms/0817. Linked List Components/817. Linked List Components.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0817. Linked List Components/817. Linked List Components_test.go b/Algorithms/0817. Linked List Components/817. Linked List Components_test.go index 4ebedd2c4..d33235bf4 100644 --- a/Algorithms/0817. Linked List Components/817. Linked List Components_test.go +++ b/Algorithms/0817. Linked List Components/817. Linked List Components_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question817 struct { @@ -67,7 +69,7 @@ func Test_Problem817(t *testing.T) { for _, q := range qs { _, p := q.ans817, q.para817 - fmt.Printf("【input】:%v 【output】:%v\n", p, numComponents(S2l(p.one), p.another)) + fmt.Printf("【input】:%v 【output】:%v\n", p, numComponents(structures.Ints2List(p.one), p.another)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0826. Most Profit Assigning Work/826. Most Profit Assigning Work.go b/Algorithms/0826. Most Profit Assigning Work/826. Most Profit Assigning Work.go index 9c3532781..7edd1c1f0 100644 --- a/Algorithms/0826. Most Profit Assigning Work/826. Most Profit Assigning Work.go +++ b/Algorithms/0826. Most Profit Assigning Work/826. Most Profit Assigning Work.go @@ -53,3 +53,10 @@ func maxProfitAssignment(difficulty []int, profit []int, worker []int) int { } return res } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0842. Split Array into Fibonacci Sequence/842. Split Array into Fibonacci Sequence.go b/Algorithms/0842. Split Array into Fibonacci Sequence/842. Split Array into Fibonacci Sequence.go index 2469ded48..78c8b9847 100644 --- a/Algorithms/0842. Split Array into Fibonacci Sequence/842. Split Array into Fibonacci Sequence.go +++ b/Algorithms/0842. Split Array into Fibonacci Sequence/842. Split Array into Fibonacci Sequence.go @@ -55,3 +55,10 @@ func findRecursiveCheck(S string, x1 int, x2 int, left int, res *[]int, isComple } return } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0845. Longest Mountain in Array/845. Longest Mountain in Array.go b/Algorithms/0845. Longest Mountain in Array/845. Longest Mountain in Array.go index aafdde4e7..0e6360286 100644 --- a/Algorithms/0845. Longest Mountain in Array/845. Longest Mountain in Array.go +++ b/Algorithms/0845. Longest Mountain in Array/845. Longest Mountain in Array.go @@ -23,3 +23,10 @@ func longestMountain(A []int) int { } return res } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0864. Shortest Path to Get All Keys/864. Shortest Path to Get All Keys.go b/Algorithms/0864. Shortest Path to Get All Keys/864. Shortest Path to Get All Keys.go index 7a42a24d0..20b77c96a 100644 --- a/Algorithms/0864. Shortest Path to Get All Keys/864. Shortest Path to Get All Keys.go +++ b/Algorithms/0864. Shortest Path to Get All Keys/864. Shortest Path to Get All Keys.go @@ -5,6 +5,13 @@ import ( "strings" ) +var dir = [][]int{ + []int{-1, 0}, + []int{0, 1}, + []int{1, 0}, + []int{0, -1}, +} + // 解法一 BFS,利用状态压缩来过滤筛选状态 func shortestPathAllKeys(grid []string) int { if len(grid) == 0 { @@ -78,6 +85,10 @@ func shortestPathAllKeys(grid []string) int { return -1 } +func isInBoard(board [][]byte, x, y int) bool { + return x >= 0 && x < len(board) && y >= 0 && y < len(board[0]) +} + // 解法二 DFS,但是超时了,剪枝条件不够强 func shortestPathAllKeys1(grid []string) int { if len(grid) == 0 { @@ -166,3 +177,10 @@ func isKey(board [][]byte, x, y int) bool { } return false } + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/0876. Middle of the Linked List/876. Middle of the Linked List.go b/Algorithms/0876. Middle of the Linked List/876. Middle of the Linked List.go index 3f13a1f04..7abfd4e6b 100644 --- a/Algorithms/0876. Middle of the Linked List/876. Middle of the Linked List.go +++ b/Algorithms/0876. Middle of the Linked List/876. Middle of the Linked List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/0876. Middle of the Linked List/876. Middle of the Linked List_test.go b/Algorithms/0876. Middle of the Linked List/876. Middle of the Linked List_test.go index ca68d1b71..c3c8a96f4 100644 --- a/Algorithms/0876. Middle of the Linked List/876. Middle of the Linked List_test.go +++ b/Algorithms/0876. Middle of the Linked List/876. Middle of the Linked List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question876 struct { @@ -50,7 +52,7 @@ func Test_Problem876(t *testing.T) { for _, q := range qs { _, p := q.ans876, q.para876 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(middleNode(S2l(p.one)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(middleNode(structures.Ints2List(p.one)))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0878. Nth Magical Number/878. Nth Magical Number.go b/Algorithms/0878. Nth Magical Number/878. Nth Magical Number.go index 1f4d696e2..6040450e1 100644 --- a/Algorithms/0878. Nth Magical Number/878. Nth Magical Number.go +++ b/Algorithms/0878. Nth Magical Number/878. Nth Magical Number.go @@ -17,3 +17,10 @@ func calNthMagicalCount(num, a, b int64) int64 { ab := a * b / gcd(a, b) return num/a + num/b - num/ab } + +func gcd(a, b int64) int64 { + for b != 0 { + a, b = b, a%b + } + return a +} diff --git a/Algorithms/0897. Increasing Order Search Tree/897. Increasing Order Search Tree.go b/Algorithms/0897. Increasing Order Search Tree/897. Increasing Order Search Tree.go index 0801136b2..68d2ad6a9 100644 --- a/Algorithms/0897. Increasing Order Search Tree/897. Increasing Order Search Tree.go +++ b/Algorithms/0897. Increasing Order Search Tree/897. Increasing Order Search Tree.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -44,3 +51,11 @@ func increasingBST1(root *TreeNode) *TreeNode { } return newRoot } + +func inorder(root *TreeNode, output *[]int) { + if root != nil { + inorder(root.Left, output) + *output = append(*output, root.Val) + inorder(root.Right, output) + } +} diff --git a/Algorithms/0897. Increasing Order Search Tree/897. Increasing Order Search Tree_test.go b/Algorithms/0897. Increasing Order Search Tree/897. Increasing Order Search Tree_test.go index f63341491..53e4af2ba 100644 --- a/Algorithms/0897. Increasing Order Search Tree/897. Increasing Order Search Tree_test.go +++ b/Algorithms/0897. Increasing Order Search Tree/897. Increasing Order Search Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question897 struct { @@ -27,18 +29,18 @@ func Test_Problem897(t *testing.T) { qs := []question897{ question897{ - para897{[]int{5, 3, 6, 2, 4, NULL, 8, 1, NULL, NULL, NULL, 7, 9}}, - ans897{[]int{1, NULL, 2, NULL, 3, NULL, 4, NULL, 5, NULL, 6, NULL, 7, NULL, 8, NULL, 9}}, + para897{[]int{5, 3, 6, 2, 4, structures.NULL, 8, 1, structures.NULL, structures.NULL, structures.NULL, 7, 9}}, + ans897{[]int{1, structures.NULL, 2, structures.NULL, 3, structures.NULL, 4, structures.NULL, 5, structures.NULL, 6, structures.NULL, 7, structures.NULL, 8, structures.NULL, 9}}, }, question897{ - para897{[]int{3, 4, 4, 5, NULL, NULL, 5, 6, NULL, NULL, 6}}, - ans897{[]int{6, NULL, 5, NULL, 4, NULL, 3, NULL, 4, NULL, 5, NULL, 6}}, + para897{[]int{3, 4, 4, 5, structures.NULL, structures.NULL, 5, 6, structures.NULL, structures.NULL, 6}}, + ans897{[]int{6, structures.NULL, 5, structures.NULL, 4, structures.NULL, 3, structures.NULL, 4, structures.NULL, 5, structures.NULL, 6}}, }, question897{ - para897{[]int{1, 2, 2, NULL, 3, 3}}, - ans897{[]int{2, NULL, 3, NULL, 1, NULL, 3, NULL, 2}}, + para897{[]int{1, 2, 2, structures.NULL, 3, 3}}, + ans897{[]int{2, structures.NULL, 3, structures.NULL, 1, structures.NULL, 3, structures.NULL, 2}}, }, question897{ @@ -53,17 +55,17 @@ func Test_Problem897(t *testing.T) { question897{ para897{[]int{1, 2, 3}}, - ans897{[]int{2, NULL, 1, NULL, 3}}, + ans897{[]int{2, structures.NULL, 1, structures.NULL, 3}}, }, question897{ para897{[]int{1, 2, 2, 3, 4, 4, 3}}, - ans897{[]int{3, NULL, 2, NULL, 4, NULL, 1, NULL, 4, NULL, 2, NULL, 3}}, + ans897{[]int{3, structures.NULL, 2, structures.NULL, 4, structures.NULL, 1, structures.NULL, 4, structures.NULL, 2, structures.NULL, 3}}, }, question897{ - para897{[]int{1, 2, 2, NULL, 3, NULL, 3}}, - ans897{[]int{2, NULL, 3, NULL, 1, NULL, 2, NULL, 3}}, + para897{[]int{1, 2, 2, structures.NULL, 3, structures.NULL, 3}}, + ans897{[]int{2, structures.NULL, 3, structures.NULL, 1, structures.NULL, 2, structures.NULL, 3}}, }, } @@ -72,8 +74,8 @@ func Test_Problem897(t *testing.T) { for _, q := range qs { _, p := q.ans897, q.para897 fmt.Printf("【input】:%v ", p) - rootOne := Ints2TreeNode(p.one) - fmt.Printf("【output】:%v \n", Tree2ints(increasingBST(rootOne))) + rootOne := structures.Ints2TreeNode(p.one) + fmt.Printf("【output】:%v \n", structures.Tree2ints(increasingBST(rootOne))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0904. Fruit Into Baskets/904. Fruit Into Baskets.go b/Algorithms/0904. Fruit Into Baskets/904. Fruit Into Baskets.go index 991d6000d..129b58f95 100644 --- a/Algorithms/0904. Fruit Into Baskets/904. Fruit Into Baskets.go +++ b/Algorithms/0904. Fruit Into Baskets/904. Fruit Into Baskets.go @@ -26,3 +26,10 @@ func totalFruit(tree []int) int { } return res } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0918. Maximum Sum Circular Subarray/918. Maximum Sum Circular Subarray.go b/Algorithms/0918. Maximum Sum Circular Subarray/918. Maximum Sum Circular Subarray.go index be73a4f8b..dd3c9a3e4 100644 --- a/Algorithms/0918. Maximum Sum Circular Subarray/918. Maximum Sum Circular Subarray.go +++ b/Algorithms/0918. Maximum Sum Circular Subarray/918. Maximum Sum Circular Subarray.go @@ -26,3 +26,10 @@ func kadane(a []int) int { } return maxSoFar } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0928. Minimize Malware Spread II/928. Minimize Malware Spread II.go b/Algorithms/0928. Minimize Malware Spread II/928. Minimize Malware Spread II.go index 70a4d453f..8f5a8aa12 100644 --- a/Algorithms/0928. Minimize Malware Spread II/928. Minimize Malware Spread II.go +++ b/Algorithms/0928. Minimize Malware Spread II/928. Minimize Malware Spread II.go @@ -66,3 +66,10 @@ func minMalwareSpread2(graph [][]int, initial []int) int { } return minIndex } + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/0952. Largest Component Size by Common Factor/952. Largest Component Size by Common Factor.go b/Algorithms/0952. Largest Component Size by Common Factor/952. Largest Component Size by Common Factor.go index 57330f4d8..48670513b 100644 --- a/Algorithms/0952. Largest Component Size by Common Factor/952. Largest Component Size by Common Factor.go +++ b/Algorithms/0952. Largest Component Size by Common Factor/952. Largest Component Size by Common Factor.go @@ -53,3 +53,10 @@ func largestComponentSize1(A []int) int { } return uf.MaxUnionCount() } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/0968. Binary Tree Cameras/968. Binary Tree Cameras.go b/Algorithms/0968. Binary Tree Cameras/968. Binary Tree Cameras.go index 8dcfae2f3..2ad7ab720 100644 --- a/Algorithms/0968. Binary Tree Cameras/968. Binary Tree Cameras.go +++ b/Algorithms/0968. Binary Tree Cameras/968. Binary Tree Cameras.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + type status int const ( diff --git a/Algorithms/0968. Binary Tree Cameras/968. Binary Tree Cameras_test.go b/Algorithms/0968. Binary Tree Cameras/968. Binary Tree Cameras_test.go index e3df925be..5f8971bd6 100644 --- a/Algorithms/0968. Binary Tree Cameras/968. Binary Tree Cameras_test.go +++ b/Algorithms/0968. Binary Tree Cameras/968. Binary Tree Cameras_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question968 struct { @@ -27,12 +29,12 @@ func Test_Problem968(t *testing.T) { qs := []question968{ question968{ - para968{[]int{0, 0, NULL, 0, 0}}, + para968{[]int{0, 0, structures.NULL, 0, 0}}, ans968{1}, }, question968{ - para968{[]int{0, 0, NULL, 0, NULL, 0, NULL, NULL, 0}}, + para968{[]int{0, 0, structures.NULL, 0, structures.NULL, 0, structures.NULL, structures.NULL, 0}}, ans968{2}, }, } @@ -42,7 +44,7 @@ func Test_Problem968(t *testing.T) { for _, q := range qs { _, p := q.ans968, q.para968 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", minCameraCover(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0976. Largest Perimeter Triangle/976. Largest Perimeter Triangle.go b/Algorithms/0976. Largest Perimeter Triangle/976. Largest Perimeter Triangle.go index 03f426cb7..50d1fc452 100644 --- a/Algorithms/0976. Largest Perimeter Triangle/976. Largest Perimeter Triangle.go +++ b/Algorithms/0976. Largest Perimeter Triangle/976. Largest Perimeter Triangle.go @@ -12,3 +12,25 @@ func largestPerimeter(A []int) int { } return 0 } + +func quickSort164(a []int, lo, hi int) { + if lo >= hi { + return + } + p := partition164(a, lo, hi) + quickSort164(a, lo, p-1) + quickSort164(a, p+1, hi) +} + +func partition164(a []int, lo, hi int) int { + pivot := a[hi] + i := lo - 1 + for j := lo; j < hi; j++ { + if a[j] < pivot { + i++ + a[j], a[i] = a[i], a[j] + } + } + a[i+1], a[hi] = a[hi], a[i+1] + return i + 1 +} diff --git a/Algorithms/0978. Longest Turbulent Subarray/978. Longest Turbulent Subarray.go b/Algorithms/0978. Longest Turbulent Subarray/978. Longest Turbulent Subarray.go index 6c04a15cb..60d3eace1 100644 --- a/Algorithms/0978. Longest Turbulent Subarray/978. Longest Turbulent Subarray.go +++ b/Algorithms/0978. Longest Turbulent Subarray/978. Longest Turbulent Subarray.go @@ -20,6 +20,20 @@ func maxTurbulenceSize(A []int) int { return maxLen } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + +func min(a int, b int) int { + if a > b { + return b + } + return a +} + // 解法二 滑动窗口 func maxTurbulenceSize1(A []int) int { if len(A) == 1 { diff --git a/Algorithms/0979. Distribute Coins in Binary Tree/979. Distribute Coins in Binary Tree.go b/Algorithms/0979. Distribute Coins in Binary Tree/979. Distribute Coins in Binary Tree.go index f8df5cb5d..553ec7ae3 100644 --- a/Algorithms/0979. Distribute Coins in Binary Tree/979. Distribute Coins in Binary Tree.go +++ b/Algorithms/0979. Distribute Coins in Binary Tree/979. Distribute Coins in Binary Tree.go @@ -1,13 +1,21 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** - * Definition for a binary tree root. + * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ + func distributeCoins(root *TreeNode) int { res := 0 distributeCoinsDFS(root, &res) @@ -22,3 +30,10 @@ func distributeCoinsDFS(root *TreeNode, res *int) int { *res += abs(left) + abs(right) return left + right + root.Val - 1 } + +func abs(a int) int { + if a > 0 { + return a + } + return -a +} diff --git a/Algorithms/0979. Distribute Coins in Binary Tree/979. Distribute Coins in Binary Tree_test.go b/Algorithms/0979. Distribute Coins in Binary Tree/979. Distribute Coins in Binary Tree_test.go index 8c900ee40..201c8500b 100644 --- a/Algorithms/0979. Distribute Coins in Binary Tree/979. Distribute Coins in Binary Tree_test.go +++ b/Algorithms/0979. Distribute Coins in Binary Tree/979. Distribute Coins in Binary Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question979 struct { @@ -37,17 +39,17 @@ func Test_Problem979(t *testing.T) { }, question979{ - para979{[]int{3, 9, 20, NULL, NULL, 15, 7}}, + para979{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, ans979{41}, }, question979{ - para979{[]int{1, 2, 3, 4, NULL, NULL, 5}}, + para979{[]int{1, 2, 3, 4, structures.NULL, structures.NULL, 5}}, ans979{11}, }, question979{ - para979{[]int{1, 2, 3, 4, NULL, 5}}, + para979{[]int{1, 2, 3, 4, structures.NULL, 5}}, ans979{11}, }, } @@ -57,7 +59,7 @@ func Test_Problem979(t *testing.T) { for _, q := range qs { _, p := q.ans979, q.para979 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", distributeCoins(root)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/0980. Unique Paths III/980. Unique Paths III.go b/Algorithms/0980. Unique Paths III/980. Unique Paths III.go index e3c12081f..f2f4809a8 100644 --- a/Algorithms/0980. Unique Paths III/980. Unique Paths III.go +++ b/Algorithms/0980. Unique Paths III/980. Unique Paths III.go @@ -1,5 +1,12 @@ package leetcode +var dir = [][]int{ + []int{-1, 0}, + []int{0, 1}, + []int{1, 0}, + []int{0, -1}, +} + func uniquePathsIII(grid [][]int) int { visited := make([][]bool, len(grid)) for i := 0; i < len(visited); i++ { diff --git a/Algorithms/0986. Interval List Intersections/986. Interval List Intersections.go b/Algorithms/0986. Interval List Intersections/986. Interval List Intersections.go index 0edc4b504..6a24c0e54 100644 --- a/Algorithms/0986. Interval List Intersections/986. Interval List Intersections.go +++ b/Algorithms/0986. Interval List Intersections/986. Interval List Intersections.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// Interval define +type Interval = structures.Interval + /** * Definition for an interval. * type Interval struct { @@ -23,3 +30,17 @@ func intervalIntersection(A []Interval, B []Interval) []Interval { } return res } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/0993. Cousins in Binary Tree/993. Cousins in Binary Tree.go b/Algorithms/0993. Cousins in Binary Tree/993. Cousins in Binary Tree.go index f5a520c06..33a9e1cee 100644 --- a/Algorithms/0993. Cousins in Binary Tree/993. Cousins in Binary Tree.go +++ b/Algorithms/0993. Cousins in Binary Tree/993. Cousins in Binary Tree.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { diff --git a/Algorithms/0993. Cousins in Binary Tree/993. Cousins in Binary Tree_test.go b/Algorithms/0993. Cousins in Binary Tree/993. Cousins in Binary Tree_test.go index 90b91cf61..4fb6a863d 100644 --- a/Algorithms/0993. Cousins in Binary Tree/993. Cousins in Binary Tree_test.go +++ b/Algorithms/0993. Cousins in Binary Tree/993. Cousins in Binary Tree_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question993 struct { @@ -34,12 +36,12 @@ func Test_Problem993(t *testing.T) { }, question993{ - para993{[]int{1, 2, 3, NULL, 4, NULL, 5}, 5, 4}, + para993{[]int{1, 2, 3, structures.NULL, 4, structures.NULL, 5}, 5, 4}, ans993{true}, }, question993{ - para993{[]int{1, 2, 3, NULL, 4}, 2, 3}, + para993{[]int{1, 2, 3, structures.NULL, 4}, 2, 3}, ans993{false}, }, } @@ -49,7 +51,7 @@ func Test_Problem993(t *testing.T) { for _, q := range qs { _, p := q.ans993, q.para993 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) + root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", isCousins(root, p.x, p.y)) } fmt.Printf("\n\n\n") diff --git a/Algorithms/1004. Max Consecutive Ones III/1004. Max Consecutive Ones III.go b/Algorithms/1004. Max Consecutive Ones III/1004. Max Consecutive Ones III.go index fd48551bf..aec1e1efb 100644 --- a/Algorithms/1004. Max Consecutive Ones III/1004. Max Consecutive Ones III.go +++ b/Algorithms/1004. Max Consecutive Ones III/1004. Max Consecutive Ones III.go @@ -20,3 +20,10 @@ func longestOnes(A []int, K int) int { } return res } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/1011. Capacity To Ship Packages Within D Days/1011. Capacity To Ship Packages Within D Days.go b/Algorithms/1011. Capacity To Ship Packages Within D Days/1011. Capacity To Ship Packages Within D Days.go index 34dd4ccb9..93873ecd8 100644 --- a/Algorithms/1011. Capacity To Ship Packages Within D Days/1011. Capacity To Ship Packages Within D Days.go +++ b/Algorithms/1011. Capacity To Ship Packages Within D Days/1011. Capacity To Ship Packages Within D Days.go @@ -22,3 +22,19 @@ func shipWithinDays(weights []int, D int) int { } return low } + +func calSum(mid, m int, nums []int) bool { + sum, count := 0, 0 + for _, v := range nums { + sum += v + if sum > mid { + sum = v + count++ + // 分成 m 块,只需要插桩 m -1 个 + if count > m-1 { + return false + } + } + } + return true +} diff --git a/Algorithms/1019. Next Greater Node In Linked List/1019. Next Greater Node In Linked List.go b/Algorithms/1019. Next Greater Node In Linked List/1019. Next Greater Node In Linked List.go index 52bd3a596..8ef54327c 100644 --- a/Algorithms/1019. Next Greater Node In Linked List/1019. Next Greater Node In Linked List.go +++ b/Algorithms/1019. Next Greater Node In Linked List/1019. Next Greater Node In Linked List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/1019. Next Greater Node In Linked List/1019. Next Greater Node In Linked List_test.go b/Algorithms/1019. Next Greater Node In Linked List/1019. Next Greater Node In Linked List_test.go index a4bc2be23..c59589d84 100644 --- a/Algorithms/1019. Next Greater Node In Linked List/1019. Next Greater Node In Linked List_test.go +++ b/Algorithms/1019. Next Greater Node In Linked List/1019. Next Greater Node In Linked List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question1019 struct { @@ -51,7 +53,7 @@ func Test_Problem1019(t *testing.T) { for _, q := range qs { _, p := q.ans1019, q.para1019 - fmt.Printf("【input】:%v 【output】:%v\n", p, nextLargerNodes(S2l(p.one))) + fmt.Printf("【input】:%v 【output】:%v\n", p, nextLargerNodes(structures.Ints2List(p.one))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/1028. Recover a Tree From Preorder Traversal/1028. Recover a Tree From Preorder Traversal.go b/Algorithms/1028. Recover a Tree From Preorder Traversal/1028. Recover a Tree From Preorder Traversal.go index 546eb8994..c3929f74e 100644 --- a/Algorithms/1028. Recover a Tree From Preorder Traversal/1028. Recover a Tree From Preorder Traversal.go +++ b/Algorithms/1028. Recover a Tree From Preorder Traversal/1028. Recover a Tree From Preorder Traversal.go @@ -4,6 +4,13 @@ import ( "strconv" ) +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -12,6 +19,7 @@ import ( * Right *TreeNode * } */ + func recoverFromPreorder(S string) *TreeNode { if len(S) == 0 { return &TreeNode{} @@ -69,3 +77,10 @@ func dfsBuildPreorderTree(S string, index, level *int, cur *TreeNode) (newIndex } return index } + +func isDigital(v byte) bool { + if v >= '0' && v <= '9' { + return true + } + return false +} diff --git a/Algorithms/1028. Recover a Tree From Preorder Traversal/1028. Recover a Tree From Preorder Traversal_test.go b/Algorithms/1028. Recover a Tree From Preorder Traversal/1028. Recover a Tree From Preorder Traversal_test.go index 38a63a327..627dfedbd 100644 --- a/Algorithms/1028. Recover a Tree From Preorder Traversal/1028. Recover a Tree From Preorder Traversal_test.go +++ b/Algorithms/1028. Recover a Tree From Preorder Traversal/1028. Recover a Tree From Preorder Traversal_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question1028 struct { @@ -32,12 +34,12 @@ func Test_Problem1028(t *testing.T) { question1028{ para1028{"1-2--3---4-5--6---7"}, - ans1028{[]int{1, 2, 5, 3, NULL, 6, NULL, 4, NULL, 7}}, + ans1028{[]int{1, 2, 5, 3, structures.NULL, 6, structures.NULL, 4, structures.NULL, 7}}, }, question1028{ para1028{"1-401--349---90--88"}, - ans1028{[]int{1, 401, NULL, 349, 88, 90}}, + ans1028{[]int{1, 401, structures.NULL, 349, 88, 90}}, }, } @@ -45,7 +47,7 @@ func Test_Problem1028(t *testing.T) { for _, q := range qs { _, p := q.ans1028, q.para1028 - fmt.Printf("【input】:%v 【output】:%v\n", p, Tree2ints(recoverFromPreorder(p.one))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.Tree2ints(recoverFromPreorder(p.one))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/1030. Matrix Cells in Distance Order/1030. Matrix Cells in Distance Order.go b/Algorithms/1030. Matrix Cells in Distance Order/1030. Matrix Cells in Distance Order.go index 0c8166c76..449f1d8c4 100644 --- a/Algorithms/1030. Matrix Cells in Distance Order/1030. Matrix Cells in Distance Order.go +++ b/Algorithms/1030. Matrix Cells in Distance Order/1030. Matrix Cells in Distance Order.go @@ -21,3 +21,17 @@ func allCellsDistOrder(R int, C int, r0 int, c0 int) [][]int { } return result } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} + +func abs(a int) int { + if a > 0 { + return a + } + return -a +} diff --git a/Algorithms/1040. Moving Stones Until Consecutive II/1040. Moving Stones Until Consecutive II.go b/Algorithms/1040. Moving Stones Until Consecutive II/1040. Moving Stones Until Consecutive II.go index 0ec750a27..c17aac58f 100644 --- a/Algorithms/1040. Moving Stones Until Consecutive II/1040. Moving Stones Until Consecutive II.go +++ b/Algorithms/1040. Moving Stones Until Consecutive II/1040. Moving Stones Until Consecutive II.go @@ -32,3 +32,17 @@ func numMovesStonesII(stones []int) []int { } return []int{minStep, maxStep} } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/1049. Last Stone Weight II/1049. Last Stone Weight II.go b/Algorithms/1049. Last Stone Weight II/1049. Last Stone Weight II.go index c93a17b0c..a8b02c306 100644 --- a/Algorithms/1049. Last Stone Weight II/1049. Last Stone Weight II.go +++ b/Algorithms/1049. Last Stone Weight II/1049. Last Stone Weight II.go @@ -20,3 +20,10 @@ func lastStoneWeightII(stones []int) int { } return sum - 2*dp[C] } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/1052. Grumpy Bookstore Owner/1052. Grumpy Bookstore Owner.go b/Algorithms/1052. Grumpy Bookstore Owner/1052. Grumpy Bookstore Owner.go index a0079f333..d0a4899af 100644 --- a/Algorithms/1052. Grumpy Bookstore Owner/1052. Grumpy Bookstore Owner.go +++ b/Algorithms/1052. Grumpy Bookstore Owner/1052. Grumpy Bookstore Owner.go @@ -38,6 +38,13 @@ func maxSatisfied1(customers []int, grumpy []int, X int) int { return res } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + func sumSatisfied(customers []int, grumpy []int, start, end int) int { sum := 0 for i := 0; i < len(customers); i++ { diff --git a/Algorithms/1105. Filling Bookcase Shelves/1105. Filling Bookcase Shelves.go b/Algorithms/1105. Filling Bookcase Shelves/1105. Filling Bookcase Shelves.go index 0cc2d2542..f1c0e3974 100644 --- a/Algorithms/1105. Filling Bookcase Shelves/1105. Filling Bookcase Shelves.go +++ b/Algorithms/1105. Filling Bookcase Shelves/1105. Filling Bookcase Shelves.go @@ -14,3 +14,17 @@ func minHeightShelves(books [][]int, shelfWidth int) int { } return dp[len(books)] } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111. Maximum Nesting Depth of Two Valid Parentheses Strings.go b/Algorithms/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111. Maximum Nesting Depth of Two Valid Parentheses Strings.go index 6268f186a..07c72d918 100644 --- a/Algorithms/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111. Maximum Nesting Depth of Two Valid Parentheses Strings.go +++ b/Algorithms/1111. Maximum Nesting Depth of Two Valid Parentheses Strings/1111. Maximum Nesting Depth of Two Valid Parentheses Strings.go @@ -32,6 +32,13 @@ func maxDepthAfterSplit(seq string) []int { return res } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + // 解法二 模拟 func maxDepthAfterSplit1(seq string) []int { stack, top, res := make([]int, len(seq)), -1, make([]int, len(seq)) diff --git a/Algorithms/1123. Lowest Common Ancestor of Deepest Leaves/1123. Lowest Common Ancestor of Deepest Leaves.go b/Algorithms/1123. Lowest Common Ancestor of Deepest Leaves/1123. Lowest Common Ancestor of Deepest Leaves.go index 4459fcc23..62f8faa70 100644 --- a/Algorithms/1123. Lowest Common Ancestor of Deepest Leaves/1123. Lowest Common Ancestor of Deepest Leaves.go +++ b/Algorithms/1123. Lowest Common Ancestor of Deepest Leaves/1123. Lowest Common Ancestor of Deepest Leaves.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// TreeNode define +type TreeNode = structures.TreeNode + /** * Definition for a binary tree node. * type TreeNode struct { @@ -8,6 +15,7 @@ package leetcode * Right *TreeNode * } */ + func lcaDeepestLeaves(root *TreeNode) *TreeNode { if root == nil { return nil @@ -29,3 +37,10 @@ func lcaDeepestLeavesDFS(lca **TreeNode, maxLevel *int, depth int, root *TreeNod } return max(depthLeft, depthRight) } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/Algorithms/1123. Lowest Common Ancestor of Deepest Leaves/1123. Lowest Common Ancestor of Deepest Leaves_test.go b/Algorithms/1123. Lowest Common Ancestor of Deepest Leaves/1123. Lowest Common Ancestor of Deepest Leaves_test.go index b219663df..9f694a2aa 100644 --- a/Algorithms/1123. Lowest Common Ancestor of Deepest Leaves/1123. Lowest Common Ancestor of Deepest Leaves_test.go +++ b/Algorithms/1123. Lowest Common Ancestor of Deepest Leaves/1123. Lowest Common Ancestor of Deepest Leaves_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question1123 struct { @@ -52,8 +54,8 @@ func Test_Problem1123(t *testing.T) { }, question1123{ - para1123{[]int{1, 2, NULL, 3, 4, NULL, 6, NULL, 5}}, - ans1123{[]int{2, 3, 4, NULL, 6, NULL, 5}}, + para1123{[]int{1, 2, structures.NULL, 3, 4, structures.NULL, 6, structures.NULL, 5}}, + ans1123{[]int{2, 3, 4, structures.NULL, 6, structures.NULL, 5}}, }, } @@ -62,8 +64,8 @@ func Test_Problem1123(t *testing.T) { for _, q := range qs { _, p := q.ans1123, q.para1123 fmt.Printf("【input】:%v ", p) - root := Ints2TreeNode(p.one) - fmt.Printf("【output】:%v \n", Tree2ints(lcaDeepestLeaves(root))) + root := structures.Ints2TreeNode(p.one) + fmt.Printf("【output】:%v \n", structures.Tree2ints(lcaDeepestLeaves(root))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171. Remove Zero Sum Consecutive Nodes from Linked List.go b/Algorithms/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171. Remove Zero Sum Consecutive Nodes from Linked List.go index 659d50127..6b650954b 100644 --- a/Algorithms/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171. Remove Zero Sum Consecutive Nodes from Linked List.go +++ b/Algorithms/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171. Remove Zero Sum Consecutive Nodes from Linked List.go @@ -1,5 +1,12 @@ package leetcode +import ( + "github.com/halfrost/LeetCode-Go/structures" +) + +// ListNode define +type ListNode = structures.ListNode + /** * Definition for singly-linked list. * type ListNode struct { diff --git a/Algorithms/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171. Remove Zero Sum Consecutive Nodes from Linked List_test.go b/Algorithms/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171. Remove Zero Sum Consecutive Nodes from Linked List_test.go index 2df0422ca..d91b59d86 100644 --- a/Algorithms/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171. Remove Zero Sum Consecutive Nodes from Linked List_test.go +++ b/Algorithms/1171. Remove Zero Sum Consecutive Nodes from Linked List/1171. Remove Zero Sum Consecutive Nodes from Linked List_test.go @@ -3,6 +3,8 @@ package leetcode import ( "fmt" "testing" + + "github.com/halfrost/LeetCode-Go/structures" ) type question1171 struct { @@ -51,7 +53,7 @@ func Test_Problem1171(t *testing.T) { for _, q := range qs { _, p := q.ans1171, q.para1171 - fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(removeZeroSumSublists(S2l(p.one)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(removeZeroSumSublists(structures.Ints2List(p.one)))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/1189. Maximum Number of Balloons/1189. Maximum Number of Balloons.go b/Algorithms/1189. Maximum Number of Balloons/1189. Maximum Number of Balloons.go index a4bcbc406..36b4207b4 100644 --- a/Algorithms/1189. Maximum Number of Balloons/1189. Maximum Number of Balloons.go +++ b/Algorithms/1189. Maximum Number of Balloons/1189. Maximum Number of Balloons.go @@ -12,3 +12,10 @@ func maxNumberOfBalloons(text string) int { // 字符 n 的频次是数组下标 13 对应的元素值 return min(fre[1], min(fre[0], min(fre[11]/2, min(fre[14]/2, fre[13])))) } + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/1208. Get Equal Substrings Within Budget/1208. Get Equal Substrings Within Budget.go b/Algorithms/1208. Get Equal Substrings Within Budget/1208. Get Equal Substrings Within Budget.go index c4668453f..0635e56d2 100644 --- a/Algorithms/1208. Get Equal Substrings Within Budget/1208. Get Equal Substrings Within Budget.go +++ b/Algorithms/1208. Get Equal Substrings Within Budget/1208. Get Equal Substrings Within Budget.go @@ -14,3 +14,17 @@ func equalSubstring(s string, t string, maxCost int) int { } return res } + +func max(a int, b int) int { + if a > b { + return a + } + return b +} + +func abs(a int) int { + if a > 0 { + return a + } + return -a +} diff --git a/Algorithms/1217. Play with Chips/1217. Play with Chips.go b/Algorithms/1217. Play with Chips/1217. Play with Chips.go index 23cade0fa..a47d76af2 100644 --- a/Algorithms/1217. Play with Chips/1217. Play with Chips.go +++ b/Algorithms/1217. Play with Chips/1217. Play with Chips.go @@ -11,3 +11,10 @@ func minCostToMoveChips(chips []int) int { } return min(odd, even) } + +func min(a int, b int) int { + if a > b { + return b + } + return a +} diff --git a/Algorithms/1235. Maximum Profit in Job Scheduling/1235. Maximum Profit in Job Scheduling.go b/Algorithms/1235. Maximum Profit in Job Scheduling/1235. Maximum Profit in Job Scheduling.go index 91eb49004..13444f3bf 100644 --- a/Algorithms/1235. Maximum Profit in Job Scheduling/1235. Maximum Profit in Job Scheduling.go +++ b/Algorithms/1235. Maximum Profit in Job Scheduling/1235. Maximum Profit in Job Scheduling.go @@ -34,6 +34,13 @@ func jobScheduling(startTime []int, endTime []int, profit []int) int { return dp[len(startTime)-1] } +func max(a int, b int) int { + if a > b { + return a + } + return b +} + type sortJobs []job func (s sortJobs) Len() int { diff --git a/structures/Heap.go b/structures/Heap.go new file mode 100644 index 000000000..995ecafd2 --- /dev/null +++ b/structures/Heap.go @@ -0,0 +1,30 @@ +package kit + +// intHeap 实现了 heap 的接口 +type intHeap []int + +func (h intHeap) Len() int { + return len(h) +} + +func (h intHeap) Less(i, j int) bool { + return h[i] < h[j] +} + +func (h intHeap) Swap(i, j int) { + h[i], h[j] = h[j], h[i] +} + +func (h *intHeap) Push(x interface{}) { + // Push 使用 *h,是因为 + // Push 增加了 h 的长度 + *h = append(*h, x.(int)) +} + +func (h *intHeap) Pop() interface{} { + // Pop 使用 *h ,是因为 + // Pop 减短了 h 的长度 + res := (*h)[len(*h)-1] + *h = (*h)[:len(*h)-1] + return res +} diff --git a/structures/Heap_test.go b/structures/Heap_test.go new file mode 100644 index 000000000..bf4f29c11 --- /dev/null +++ b/structures/Heap_test.go @@ -0,0 +1,30 @@ +package kit + +import ( + "container/heap" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_intHeap(t *testing.T) { + ast := assert.New(t) + + ih := new(intHeap) + heap.Init(ih) + + heap.Push(ih, 1) + heap.Pop(ih) + + begin, end := 0, 10 + for i := begin; i < end; i++ { + heap.Push(ih, i) + ast.Equal(0, (*ih)[0], "插入 %d 后的最小值却是 %d,ih=%v", i, (*ih)[0], (*ih)) + } + + for i := begin; i < end; i++ { + fmt.Println(i, *ih) + ast.Equal(i, heap.Pop(ih), "Pop 后 ih=%v", (*ih)) + } +} diff --git a/structures/Interval.go b/structures/Interval.go new file mode 100644 index 000000000..660550f0a --- /dev/null +++ b/structures/Interval.go @@ -0,0 +1,53 @@ +package kit + +// Interval 提供区间表示 +type Interval struct { + Start int + End int +} + +// Interval2Ints 把 Interval 转换成 整型切片 +func Interval2Ints(i Interval) []int { + return []int{i.Start, i.End} +} + +// IntervalSlice2Intss 把 []Interval 转换成 [][]int +func IntervalSlice2Intss(is []Interval) [][]int { + res := make([][]int, 0, len(is)) + for i := range is { + res = append(res, Interval2Ints(is[i])) + } + return res +} + +// Intss2IntervalSlice 把 [][]int 转换成 []Interval +func Intss2IntervalSlice(intss [][]int) []Interval { + res := make([]Interval, 0, len(intss)) + for _, ints := range intss { + res = append(res, Interval{Start: ints[0], End: ints[1]}) + } + return res +} + +// QuickSort define +func QuickSort(a []Interval, lo, hi int) { + if lo >= hi { + return + } + p := partitionSort(a, lo, hi) + QuickSort(a, lo, p-1) + QuickSort(a, p+1, hi) +} + +func partitionSort(a []Interval, lo, hi int) int { + pivot := a[hi] + i := lo - 1 + for j := lo; j < hi; j++ { + if (a[j].Start < pivot.Start) || (a[j].Start == pivot.Start && a[j].End < pivot.End) { + i++ + a[j], a[i] = a[i], a[j] + } + } + a[i+1], a[hi] = a[hi], a[i+1] + return i + 1 +} diff --git a/structures/Interval_test.go b/structures/Interval_test.go new file mode 100644 index 000000000..87a562e6c --- /dev/null +++ b/structures/Interval_test.go @@ -0,0 +1,59 @@ +package kit + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_Interval2Ints(t *testing.T) { + ast := assert.New(t) + + actual := Interval2Ints(Interval{Start: 1, End: 2}) + expected := []int{1, 2} + ast.Equal(expected, actual) +} + +func Test_IntervalSlice2Intss(t *testing.T) { + ast := assert.New(t) + + actual := IntervalSlice2Intss( + []Interval{ + Interval{ + Start: 1, + End: 2, + }, + Interval{ + Start: 3, + End: 4, + }, + }, + ) + expected := [][]int{ + []int{1, 2}, + []int{3, 4}, + } + + ast.Equal(expected, actual) +} +func Test_Intss2IntervalSlice(t *testing.T) { + ast := assert.New(t) + + expected := []Interval{ + Interval{ + Start: 1, + End: 2, + }, + Interval{ + Start: 3, + End: 4, + }, + } + actual := Intss2IntervalSlice([][]int{ + []int{1, 2}, + []int{3, 4}, + }, + ) + + ast.Equal(expected, actual) +} diff --git a/structures/ListNode.go b/structures/ListNode.go new file mode 100644 index 000000000..96ac70955 --- /dev/null +++ b/structures/ListNode.go @@ -0,0 +1,82 @@ +package kit + +import ( + "fmt" +) + +// ListNode 是链接节点 +// 这个不能复制到*_test.go文件中。会导致Travis失败 +type ListNode struct { + Val int + Next *ListNode +} + +// List2Ints convert List to []int +func List2Ints(head *ListNode) []int { + // 链条深度限制,链条深度超出此限制,会 panic + limit := 100 + + times := 0 + + res := []int{} + for head != nil { + times++ + if times > limit { + msg := fmt.Sprintf("链条深度超过%d,可能出现环状链条。请检查错误,或者放宽 l2s 函数中 limit 的限制。", limit) + panic(msg) + } + + res = append(res, head.Val) + head = head.Next + } + + return res +} + +// Ints2List convert []int to List +func Ints2List(nums []int) *ListNode { + if len(nums) == 0 { + return nil + } + + l := &ListNode{} + t := l + for _, v := range nums { + t.Next = &ListNode{Val: v} + t = t.Next + } + return l.Next +} + +// GetNodeWith returns the first node with val +func (l *ListNode) GetNodeWith(val int) *ListNode { + res := l + for res != nil { + if res.Val == val { + break + } + res = res.Next + } + return res +} + +// Ints2ListWithCycle returns a list whose tail point to pos-indexed node +// head's index is 0 +// if pos = -1, no cycle +func Ints2ListWithCycle(nums []int, pos int) *ListNode { + head := Ints2List(nums) + if pos == -1 { + return head + } + c := head + for pos > 0 { + c = c.Next + pos-- + } + tail := c + for tail.Next != nil { + tail = tail.Next + } + tail.Next = c + return head +} diff --git a/structures/ListNode_test.go b/structures/ListNode_test.go new file mode 100644 index 000000000..64cc2a020 --- /dev/null +++ b/structures/ListNode_test.go @@ -0,0 +1,68 @@ +package kit + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_l2s(t *testing.T) { + ast := assert.New(t) + ast.Equal([]int{}, List2Ints(nil), "输入nil,没有返回[]int{}") + + one2three := &ListNode{ + Val: 1, + Next: &ListNode{ + Val: 2, + Next: &ListNode{ + Val: 3, + }, + }, + } + ast.Equal([]int{1, 2, 3}, List2Ints(one2three), "没有成功地转换成[]int") + + limit := 100 + overLimitList := Ints2List(make([]int, limit+1)) + ast.Panics(func() { List2Ints(overLimitList) }, "转换深度超过 %d 限制的链条,没有 panic", limit) +} + +func Test_s2l(t *testing.T) { + ast := assert.New(t) + ast.Nil(Ints2List([]int{}), "输入[]int{},没有返回nil") + + ln := Ints2List([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}) + i := 1 + for ln != nil { + ast.Equal(i, ln.Val, "对应的值不对") + ln = ln.Next + i++ + } +} + +func Test_getNodeWith(t *testing.T) { + ast := assert.New(t) + // + ln := Ints2List([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}) + val := 10 + node := &ListNode{ + Val: val, + } + tail := ln + for tail.Next != nil { + tail = tail.Next + } + tail.Next = node + expected := node + actual := ln.GetNodeWith(val) + ast.Equal(expected, actual) +} + +func Test_Ints2ListWithCycle(t *testing.T) { + ast := assert.New(t) + ints := []int{1, 2, 3} + l := Ints2ListWithCycle(ints, -1) + ast.Equal(ints, List2Ints(l)) + + l = Ints2ListWithCycle(ints, 1) + ast.Panics(func() { List2Ints(l) }) +} diff --git a/structures/NestedInteger.go b/structures/NestedInteger.go new file mode 100644 index 000000000..7c5c657b1 --- /dev/null +++ b/structures/NestedInteger.go @@ -0,0 +1,37 @@ +package kit + +// NestedInteger is the interface that allows for creating nested lists. +// You should not implement it, or speculate about its implementation +type NestedInteger struct { + Num int + Ns []*NestedInteger +} + +// IsInteger Return true if this NestedInteger holds a single integer, rather than a nested list. +func (n NestedInteger) IsInteger() bool { + return n.Ns == nil +} + +// GetInteger Return the single integer that this NestedInteger holds, if it holds a single integer +// The result is undefined if this NestedInteger holds a nested list +// So before calling this method, you should have a check +func (n NestedInteger) GetInteger() int { + return n.Num +} + +// SetInteger Set this NestedInteger to hold a single integer. +func (n *NestedInteger) SetInteger(value int) { + n.Num = value +} + +// Add Set this NestedInteger to hold a nested list and adds a nested integer to it. +func (n *NestedInteger) Add(elem NestedInteger) { + n.Ns = append(n.Ns, &elem) +} + +// GetList Return the nested list that this NestedInteger holds, if it holds a nested list +// The list length is zero if this NestedInteger holds a single integer +// You can access NestedInteger's List element directly if you want to modify it +func (n NestedInteger) GetList() []*NestedInteger { + return n.Ns +} diff --git a/structures/NestedInterger_test.go b/structures/NestedInterger_test.go new file mode 100644 index 000000000..8ce2701ad --- /dev/null +++ b/structures/NestedInterger_test.go @@ -0,0 +1,30 @@ +package kit + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_NestedInteger(t *testing.T) { + ast := assert.New(t) + + n := NestedInteger{} + + ast.True(n.IsInteger()) + + n.SetInteger(1) + ast.Equal(1, n.GetInteger()) + + elem := NestedInteger{Num: 1} + + expected := NestedInteger{ + Num: 1, + Ns: []*NestedInteger{&elem}, + } + n.Add(elem) + + ast.Equal(expected, n) + + ast.Equal(expected.Ns, n.GetList()) +} diff --git a/structures/Point.go b/structures/Point.go new file mode 100644 index 000000000..2b0cfc810 --- /dev/null +++ b/structures/Point.go @@ -0,0 +1,27 @@ +package kit + +// Point 定义了一个二维坐标点 +type Point struct { + X, Y int +} + +// Intss2Points 把 [][]int 转换成 []Point +func Intss2Points(points [][]int) []Point { + res := make([]Point, len(points)) + for i, p := range points { + res[i] = Point{ + X: p[0], + Y: p[1], + } + } + return res +} + +// Points2Intss 把 []Point 转换成 [][]int +func Points2Intss(points []Point) [][]int { + res := make([][]int, len(points)) + for i, p := range points { + res[i] = []int{p.X, p.Y} + } + return res +} diff --git a/structures/Point_test.go b/structures/Point_test.go new file mode 100644 index 000000000..9a2ce89fc --- /dev/null +++ b/structures/Point_test.go @@ -0,0 +1,78 @@ +package kit + +import ( + "reflect" + "testing" +) + +func Test_Intss2Points(t *testing.T) { + type args struct { + points [][]int + } + tests := []struct { + name string + args args + want []Point + }{ + { + "测试 [][]int 转换成 []Point ", + args{ + [][]int{ + {1, 0}, + {2, 0}, + {3, 0}, + {4, 0}, + {5, 0}, + }, + }, + []Point{ + Point{X: 1, Y: 0}, + Point{X: 2, Y: 0}, + Point{X: 3, Y: 0}, + Point{X: 4, Y: 0}, + Point{X: 5, Y: 0}, + }, + }, + } + for _, tt := range tests { + if got := Intss2Points(tt.args.points); !reflect.DeepEqual(got, tt.want) { + t.Errorf("%q. intss2Points() = %v, want %v", tt.name, got, tt.want) + } + } +} + +func Test_Points2Intss(t *testing.T) { + type args struct { + points []Point + } + tests := []struct { + name string + args args + want [][]int + }{ + { + "测试 [][]int 转换成 []Point ", + args{ + []Point{ + Point{X: 1, Y: 0}, + Point{X: 2, Y: 0}, + Point{X: 3, Y: 0}, + Point{X: 4, Y: 0}, + Point{X: 5, Y: 0}, + }, + }, + [][]int{ + {1, 0}, + {2, 0}, + {3, 0}, + {4, 0}, + {5, 0}, + }, + }, + } + for _, tt := range tests { + if got := Points2Intss(tt.args.points); !reflect.DeepEqual(got, tt.want) { + t.Errorf("%q. Points2Intss() = %v, want %v", tt.name, got, tt.want) + } + } +} diff --git a/structures/PriorityQueue.go b/structures/PriorityQueue.go new file mode 100644 index 000000000..9177cf602 --- /dev/null +++ b/structures/PriorityQueue.go @@ -0,0 +1,54 @@ +package kit + +// This example demonstrates a priority queue built using the heap interface. + +import ( + "container/heap" +) + +// entry 是 priorityQueue 中的元素 +type entry struct { + key string + priority int + // index 是 entry 在 heap 中的索引号 + // entry 加入 Priority Queue 后, Priority 会变化时,很有用 + // 如果 entry.priority 一直不变的话,可以删除 index + index int +} + +// PQ implements heap.Interface and holds entries. +type PQ []*entry + +func (pq PQ) Len() int { return len(pq) } + +func (pq PQ) Less(i, j int) bool { + return pq[i].priority < pq[j].priority +} + +func (pq PQ) Swap(i, j int) { + pq[i], pq[j] = pq[j], pq[i] + pq[i].index = i + pq[j].index = j +} + +// Push 往 pq 中放 entry +func (pq *PQ) Push(x interface{}) { + temp := x.(*entry) + temp.index = len(*pq) + *pq = append(*pq, temp) +} + +// Pop 从 pq 中取出最优先的 entry +func (pq *PQ) Pop() interface{} { + temp := (*pq)[len(*pq)-1] + temp.index = -1 // for safety + *pq = (*pq)[0 : len(*pq)-1] + return temp +} + +// update modifies the priority and value of an entry in the queue. +func (pq *PQ) update(entry *entry, value string, priority int) { + entry.key = value + entry.priority = priority + heap.Fix(pq, entry.index) +} diff --git a/structures/PriorityQueue_test.go b/structures/PriorityQueue_test.go new file mode 100644 index 000000000..576a521f2 --- /dev/null +++ b/structures/PriorityQueue_test.go @@ -0,0 +1,53 @@ +package kit + +import ( + "container/heap" + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_priorityQueue(t *testing.T) { + ast := assert.New(t) + + // Some items and their priorities. + items := map[string]int{ + "banana": 2, "apple": 1, "pear": 3, + } + + // Create a priority queue, put the items in it, and + // establish the priority queue (heap) invariants. + pq := make(PQ, len(items)) + i := 0 + for value, priority := range items { + pq[i] = &entry{ + key: value, + priority: priority, + index: i, + } + i++ + } + heap.Init(&pq) + + // Insert a new item and then modify its priority. + it := &entry{ + key: "orange", + priority: 5, + } + heap.Push(&pq, it) + pq.update(it, it.key, 0) + + // Some items and their priorities. + expected := []string{ + "orange", + "apple", + "banana", + "pear", + } + + // Take the items out; they arrive in decreasing priority order. + for pq.Len() > 0 { + it := heap.Pop(&pq).(*entry) + ast.Equal(expected[it.priority], it.key) + } +} diff --git a/structures/Queue.go b/structures/Queue.go new file mode 100644 index 000000000..495d39661 --- /dev/null +++ b/structures/Queue.go @@ -0,0 +1,33 @@ +package kit + +// Queue 是用于存放 int 的队列 +type Queue struct { + nums []int +} + +// NewQueue 返回 *kit.Queue +func NewQueue() *Queue { + return &Queue{nums: []int{}} +} + +// Push 把 n 放入队列 +func (q *Queue) Push(n int) { + q.nums = append(q.nums, n) +} + +// Pop 从 q 中取出最先进入队列的值 +func (q *Queue) Pop() int { + res := q.nums[0] + q.nums = q.nums[1:] + return res +} + +// Len 返回 q 的长度 +func (q *Queue) Len() int { + return len(q.nums) +} + +// IsEmpty 反馈 q 是否为空 +func (q *Queue) IsEmpty() bool { + return q.Len() == 0 +} diff --git a/structures/Queue_test.go b/structures/Queue_test.go new file mode 100644 index 000000000..8fac7eb20 --- /dev/null +++ b/structures/Queue_test.go @@ -0,0 +1,27 @@ +package kit + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_Queue(t *testing.T) { + ast := assert.New(t) + + q := NewQueue() + ast.True(q.IsEmpty(), "检查新建的 q 是否为空") + + start, end := 0, 100 + + for i := start; i < end; i++ { + q.Push(i) + ast.Equal(i-start+1, q.Len(), "Push 后检查 q 的长度。") + } + + for i := start; i < end; i++ { + ast.Equal(i, q.Pop(), "从 q 中 pop 出数来。") + } + + ast.True(q.IsEmpty(), "检查 Pop 完毕后的 q 是否为空") +} diff --git a/structures/Stack.go b/structures/Stack.go new file mode 100644 index 000000000..39d150350 --- /dev/null +++ b/structures/Stack.go @@ -0,0 +1,33 @@ +package kit + +// Stack 是用于存放 int 的 栈 +type Stack struct { + nums []int +} + +// NewStack 返回 *kit.Stack +func NewStack() *Stack { + return &Stack{nums: []int{}} +} + +// Push 把 n 放入 栈 +func (s *Stack) Push(n int) { + s.nums = append(s.nums, n) +} + +// Pop 从 s 中取出最后放入 栈 的值 +func (s *Stack) Pop() int { + res := s.nums[len(s.nums)-1] + s.nums = s.nums[:len(s.nums)-1] + return res +} + +// Len 返回 s 的长度 +func (s *Stack) Len() int { + return len(s.nums) +} + +// IsEmpty 反馈 s 是否为空 +func (s *Stack) IsEmpty() bool { + return s.Len() == 0 +} diff --git a/structures/Stack_test.go b/structures/Stack_test.go new file mode 100644 index 000000000..e6ebdcc0d --- /dev/null +++ b/structures/Stack_test.go @@ -0,0 +1,27 @@ +package kit + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_Stack(t *testing.T) { + ast := assert.New(t) + + s := NewStack() + ast.True(s.IsEmpty(), "检查新建的 s 是否为空") + + start, end := 0, 100 + + for i := start; i < end; i++ { + s.Push(i) + ast.Equal(i-start+1, s.Len(), "Push 后检查 q 的长度。") + } + + for i := end - 1; i >= start; i-- { + ast.Equal(i, s.Pop(), "从 s 中 pop 出数来。") + } + + ast.True(s.IsEmpty(), "检查 Pop 完毕后的 s 是否为空") +} diff --git a/structures/TreeNode.go b/structures/TreeNode.go new file mode 100644 index 000000000..56e376121 --- /dev/null +++ b/structures/TreeNode.go @@ -0,0 +1,233 @@ +package kit + +import ( + "fmt" +) + +// TreeNode is tree's node +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +// NULL 方便添加测试数据 +var NULL = -1 << 63 + +// Ints2TreeNode 利用 []int 生成 *TreeNode +func Ints2TreeNode(ints []int) *TreeNode { + n := len(ints) + if n == 0 { + return nil + } + + root := &TreeNode{ + Val: ints[0], + } + + queue := make([]*TreeNode, 1, n*2) + queue[0] = root + + i := 1 + for i < n { + node := queue[0] + queue = queue[1:] + + if i < n && ints[i] != NULL { + node.Left = &TreeNode{Val: ints[i]} + queue = append(queue, node.Left) + } + i++ + + if i < n && ints[i] != NULL { + node.Right = &TreeNode{Val: ints[i]} + queue = append(queue, node.Right) + } + i++ + } + + return root +} + +// GetTargetNode 返回 Val = target 的 TreeNode +// root 中一定有 node.Val = target +func GetTargetNode(root *TreeNode, target int) *TreeNode { + if root == nil || root.Val == target { + return root + } + + res := GetTargetNode(root.Left, target) + if res != nil { + return res + } + return GetTargetNode(root.Right, target) +} + +func indexOf(val int, nums []int) int { + for i, v := range nums { + if v == val { + return i + } + } + + msg := fmt.Sprintf("%d 不存在于 %v 中", val, nums) + panic(msg) +} + +// PreIn2Tree 把 preorder 和 inorder 切片转换成 二叉树 +func PreIn2Tree(pre, in []int) *TreeNode { + if len(pre) != len(in) { + panic("preIn2Tree 中两个切片的长度不相等") + } + + if len(in) == 0 { + return nil + } + + res := &TreeNode{ + Val: pre[0], + } + + if len(in) == 1 { + return res + } + + idx := indexOf(res.Val, in) + + res.Left = PreIn2Tree(pre[1:idx+1], in[:idx]) + res.Right = PreIn2Tree(pre[idx+1:], in[idx+1:]) + + return res +} + +// InPost2Tree 把 inorder 和 postorder 切片转换成 二叉树 +func InPost2Tree(in, post []int) *TreeNode { + if len(post) != len(in) { + panic("inPost2Tree 中两个切片的长度不相等") + } + + if len(in) == 0 { + return nil + } + + res := &TreeNode{ + Val: post[len(post)-1], + } + + if len(in) == 1 { + return res + } + + idx := indexOf(res.Val, in) + + res.Left = InPost2Tree(in[:idx], post[:idx]) + res.Right = InPost2Tree(in[idx+1:], post[idx:len(post)-1]) + + return res +} + +// Tree2Preorder 把 二叉树 转换成 preorder 的切片 +func Tree2Preorder(root *TreeNode) []int { + if root == nil { + return nil + } + + if root.Left == nil && root.Right == nil { + return []int{root.Val} + } + + res := []int{root.Val} + res = append(res, Tree2Preorder(root.Left)...) + res = append(res, Tree2Preorder(root.Right)...) + + return res +} + +// Tree2Inorder 把 二叉树转换成 inorder 的切片 +func Tree2Inorder(root *TreeNode) []int { + if root == nil { + return nil + } + + if root.Left == nil && root.Right == nil { + return []int{root.Val} + } + + res := Tree2Inorder(root.Left) + res = append(res, root.Val) + res = append(res, Tree2Inorder(root.Right)...) + + return res +} + +// Tree2Postorder 把 二叉树 转换成 postorder 的切片 +func Tree2Postorder(root *TreeNode) []int { + if root == nil { + return nil + } + + if root.Left == nil && root.Right == nil { + return []int{root.Val} + } + + res := Tree2Postorder(root.Left) + res = append(res, Tree2Postorder(root.Right)...) + res = append(res, root.Val) + + return res +} + +// Equal return ture if tn == a +func (tn *TreeNode) Equal(a *TreeNode) bool { + if tn == nil && a == nil { + return true + } + + if tn == nil || a == nil || tn.Val != a.Val { + return false + } + + return tn.Left.Equal(a.Left) && tn.Right.Equal(a.Right) +} + +// Tree2ints 把 *TreeNode 按照行还原成 []int +func Tree2ints(tn *TreeNode) []int { + res := make([]int, 0, 1024) + + queue := []*TreeNode{tn} + + for len(queue) > 0 { + size := len(queue) + for i := 0; i < size; i++ { + nd := queue[i] + if nd == nil { + res = append(res, NULL) + } else { + res = append(res, nd.Val) + queue = append(queue, nd.Left, nd.Right) + } + } + queue = queue[size:] + } + + i := len(res) + for i > 0 && res[i-1] == NULL { + i-- + } + + return res[:i] +} + +// T2s convert *TreeNode to []int +func T2s(head *TreeNode, array *[]int) { + fmt.Printf("运行到这里了 head = %v array = %v\n", head, array) + // fmt.Printf("****array = %v\n", array) + // fmt.Printf("****head = %v\n", head.Val) + *array = append(*array, head.Val) + if head.Left != nil { + T2s(head.Left, array) + } + if head.Right != nil { + T2s(head.Right, array) + } +} diff --git a/structures/TreeNode_test.go b/structures/TreeNode_test.go new file mode 100644 index 000000000..ab5d15a2d --- /dev/null +++ b/structures/TreeNode_test.go @@ -0,0 +1,166 @@ +package kit + +import ( + "reflect" + "testing" + + "github.com/stretchr/testify/assert" +) + +var ( + // 同一个 TreeNode 的不同表达方式 + // 1 + // / \ + // 2 3 + // / \ / \ + // 4 5 6 7 + LeetCodeOrder = []int{1, 2, 3, 4, 5, 6, 7} + preOrder = []int{1, 2, 4, 5, 3, 6, 7} + inOrder = []int{4, 2, 5, 1, 6, 3, 7} + postOrder = []int{4, 5, 2, 6, 7, 3, 1} +) + +func Test_Ints2TreeNode(t *testing.T) { + ast := assert.New(t) + + expected := PreIn2Tree(preOrder, inOrder) + actual := Ints2TreeNode(LeetCodeOrder) + ast.Equal(expected, actual) + + actual = Ints2TreeNode([]int{}) + ast.Nil(actual) +} + +func Test_preIn2Tree(t *testing.T) { + ast := assert.New(t) + + actual := Tree2Postorder(PreIn2Tree(preOrder, inOrder)) + expected := postOrder + ast.Equal(expected, actual) + + ast.Panics(func() { PreIn2Tree([]int{1}, []int{}) }) + + ast.Nil(PreIn2Tree([]int{}, []int{})) +} + +func Test_inPost2Tree(t *testing.T) { + ast := assert.New(t) + + actual := Tree2Preorder(InPost2Tree(inOrder, postOrder)) + expected := preOrder + ast.Equal(expected, actual) + + ast.Panics(func() { InPost2Tree([]int{1}, []int{}) }) + + ast.Nil(InPost2Tree([]int{}, []int{})) +} + +func Test_tree2Ints(t *testing.T) { + ast := assert.New(t) + root := PreIn2Tree(preOrder, inOrder) + + ast.Equal(preOrder, Tree2Preorder(root)) + ast.Nil(Tree2Preorder(nil)) + + ast.Equal(inOrder, Tree2Inorder(root)) + ast.Nil(Tree2Inorder(nil)) + + ast.Equal(postOrder, Tree2Postorder(root)) + ast.Nil(Tree2Postorder(nil)) +} + +func Test_indexOf(t *testing.T) { + ast := assert.New(t) + + ast.Equal(1, indexOf(1, []int{0, 1, 2, 3})) + + ast.Panics(func() { indexOf(0, []int{1, 2, 3}) }) +} + +func Test_TreeNode_Equal(t *testing.T) { + type args struct { + a *TreeNode + } + tests := []struct { + name string + fields args + args args + want bool + }{ + + { + "相等", + args{Ints2TreeNode([]int{1, 2, 3, 4, 5})}, + args{Ints2TreeNode([]int{1, 2, 3, 4, 5})}, + true, + }, + + { + "不相等", + args{Ints2TreeNode([]int{1, 2, 3, 4, 5})}, + args{Ints2TreeNode([]int{1, 2, 3, NULL, 5})}, + false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tn := tt.fields.a + if got := tn.Equal(tt.args.a); got != tt.want { + t.Errorf("TreeNode.Equal() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_GetTargetNode(t *testing.T) { + ints := []int{3, 5, 1, 6, 2, 0, 8, NULL, NULL, 7, 4} + root := Ints2TreeNode(ints) + + type args struct { + root *TreeNode + target int + } + tests := []struct { + name string + args args + want *TreeNode + }{ + + { + "找到 root.Right.Right", + args{ + root: root, + target: 8, + }, + root.Right.Right, + }, + + { + "找到 root.Left.Left", + args{ + root: root, + target: 6, + }, + root.Left.Left, + }, + + // + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := GetTargetNode(tt.args.root, tt.args.target); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetTargetNode() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_Tree2ints(t *testing.T) { + ast := assert.New(t) + + root := PreIn2Tree(preOrder, inOrder) + actual := LeetCodeOrder + expected := Tree2ints(root) + ast.Equal(expected, actual) +}