diff --git a/Algorithms/0007. Reverse Integer/7. Reverse Integer.go b/Algorithms/0007. Reverse Integer/7. Reverse Integer.go index c40af446..f8900cbe 100644 --- a/Algorithms/0007. Reverse Integer/7. Reverse Integer.go +++ b/Algorithms/0007. Reverse Integer/7. Reverse Integer.go @@ -1,6 +1,6 @@ package leetcode -func reverse_7(x int) int { +func reverse7(x int) int { tmp := 0 for x != 0 { tmp = tmp*10 + x%10 diff --git a/Algorithms/0007. Reverse Integer/7. Reverse Integer_test.go b/Algorithms/0007. Reverse Integer/7. Reverse Integer_test.go index 8bee7abf..8fb8e594 100644 --- a/Algorithms/0007. Reverse Integer/7. Reverse Integer_test.go +++ b/Algorithms/0007. Reverse Integer/7. Reverse Integer_test.go @@ -51,7 +51,7 @@ func Test_Problem7(t *testing.T) { for _, q := range qs { _, p := q.ans7, q.para7 - fmt.Printf("【input】:%v 【output】:%v\n", p.one, reverse_7(p.one)) + fmt.Printf("【input】:%v 【output】:%v\n", p.one, reverse7(p.one)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0015. 3Sum/15. 3Sum.go b/Algorithms/0015. 3Sum/15. 3Sum.go index 30417f50..ea643c8c 100644 --- a/Algorithms/0015. 3Sum/15. 3Sum.go +++ b/Algorithms/0015. 3Sum/15. 3Sum.go @@ -12,7 +12,7 @@ func threeSum(nums []int) [][]int { } uniqNums := []int{} - for key, _ := range counter { + for key := range counter { uniqNums = append(uniqNums, key) } sort.Ints(uniqNums) diff --git a/Algorithms/0016. 3Sum Closest/16. 3Sum Closest.go b/Algorithms/0016. 3Sum Closest/16. 3Sum Closest.go index 0c3db8eb..0beaac70 100644 --- a/Algorithms/0016. 3Sum Closest/16. 3Sum Closest.go +++ b/Algorithms/0016. 3Sum Closest/16. 3Sum Closest.go @@ -30,7 +30,7 @@ func threeSumClosest(nums []int, target int) int { } // 解法二 暴力解法 O(n^3) -func threeSumClosest_(nums []int, target int) int { +func threeSumClosest1(nums []int, target int) int { res, difference := 0, math.MaxInt16 for i := 0; i < len(nums); i++ { for j := i + 1; j < len(nums); j++ { diff --git a/Algorithms/0018. 4Sum/18. 4Sum.go b/Algorithms/0018. 4Sum/18. 4Sum.go index c3a43436..38f8da3d 100644 --- a/Algorithms/0018. 4Sum/18. 4Sum.go +++ b/Algorithms/0018. 4Sum/18. 4Sum.go @@ -10,7 +10,7 @@ func fourSum(nums []int, target int) [][]int { } uniqNums := []int{} - for key, _ := range counter { + for key := range counter { uniqNums = append(uniqNums, key) } sort.Ints(uniqNums) 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 5642bcc7..63a4e285 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 @@ -29,7 +29,7 @@ func removeNthFromEnd(head *ListNode, n int) *ListNode { } // 解法二 -func removeNthFromEnd_(head *ListNode, n int) *ListNode { +func removeNthFromEnd1(head *ListNode, n int) *ListNode { if head == nil { return nil } 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 8aa871d9..e3a71d9c 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 @@ -17,56 +17,7 @@ func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { if l1.Val < l2.Val { l1.Next = mergeTwoLists(l1.Next, l2) return l1 - } else { - l2.Next = mergeTwoLists(l1, l2.Next) - return l2 } - // if l1 == nil && l2 == nil { - // return nil - // } - // head := &ListNode{Val: 0, Next: nil} - // current := head - // var currentl1, currentl2 *ListNode - // for l1 != nil || l2 != nil { - // if l1 != nil { - // currentl1 = &ListNode{Val: l1.Val, Next: nil} - // } - // if l2 != nil { - // currentl2 = &ListNode{Val: l2.Val, Next: nil} - // } - - // if l1 == nil && l2 != nil { - // current.Next = currentl2 - // current = currentl2 - // l2 = l2.Next - // continue - // } else if l2 == nil && l1 != nil { - // current.Next = currentl1 - // current = currentl1 - // l1 = l1.Next - // continue - // } else if l2 == nil && l1 == nil { - // return head.Next - // } else { - // if currentl1.Val < currentl2.Val { - // current.Next = currentl1 - // current = currentl1 - // l1 = l1.Next - // continue - // } else if currentl1.Val == currentl2.Val { - // current.Next = currentl2 - // currentl2.Next = currentl1 - // current = currentl1 - // l1 = l1.Next - // l2 = l2.Next - // continue - // } else { - // current.Next = currentl2 - // current = currentl2 - // l2 = l2.Next - // continue - // } - // } - // } - // return head.Next + l2.Next = mergeTwoLists(l1, l2.Next) + return l2 } 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 23f941c9..5ae46b40 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 @@ -31,8 +31,7 @@ func mergeTwoLists1(l1 *ListNode, l2 *ListNode) *ListNode { if l1.Val < l2.Val { l1.Next = mergeTwoLists1(l1.Next, l2) return l1 - } else { - l2.Next = mergeTwoLists1(l1, l2.Next) - return l2 } + l2.Next = mergeTwoLists1(l1, l2.Next) + return l2 } diff --git a/Algorithms/0026. Remove Duplicates from Sorted Array/26. Remove Duplicates from Sorted Array.go b/Algorithms/0026. Remove Duplicates from Sorted Array/26. Remove Duplicates from Sorted Array.go index 8cdd3c02..6e62edde 100644 --- a/Algorithms/0026. Remove Duplicates from Sorted Array/26. Remove Duplicates from Sorted Array.go +++ b/Algorithms/0026. Remove Duplicates from Sorted Array/26. Remove Duplicates from Sorted Array.go @@ -14,13 +14,13 @@ func removeDuplicates(nums []int) int { } } nums[last+1] = nums[finder] - last += 1 + last++ } return last + 1 } // 解法二 -func removeDuplicates_(nums []int) int { +func removeDuplicates1(nums []int) int { if len(nums) == 0 { return 0 } @@ -32,14 +32,14 @@ func removeDuplicates_(nums []int) int { break } if nums[i+1] == nums[i] { - removeElement_(nums, i+1, nums[i]) + removeElement1(nums, i+1, nums[i]) // fmt.Printf("此时 num = %v length = %v\n", nums, length) } } return i + 1 } -func removeElement_(nums []int, start, val int) int { +func removeElement1(nums []int, start, val int) int { if len(nums) == 0 { return 0 } diff --git a/Algorithms/0028. Implement strStr()/28. Implement strStr().go b/Algorithms/0028. Implement strStr()/28. Implement strStr().go index 9b033e39..2e688fb1 100644 --- a/Algorithms/0028. Implement strStr()/28. Implement strStr().go +++ b/Algorithms/0028. Implement strStr()/28. Implement strStr().go @@ -20,6 +20,6 @@ func strStr(haystack string, needle string) int { } // 解法二 -func strStr_(haystack string, needle string) int { +func strStr1(haystack string, needle string) int { return strings.Index(haystack, needle) } diff --git a/Algorithms/0036. Valid Sudoku/36. Valid Sudoku.go b/Algorithms/0036. Valid Sudoku/36. Valid Sudoku.go index f34a96cc..9fb433c2 100644 --- a/Algorithms/0036. Valid Sudoku/36. Valid Sudoku.go +++ b/Algorithms/0036. Valid Sudoku/36. Valid Sudoku.go @@ -60,7 +60,7 @@ func isValidSudoku(board [][]byte) bool { } // 解法二 添加缓存,时间复杂度 O(n^2) -func isValidSudoku_(board [][]byte) bool { +func isValidSudoku1(board [][]byte) bool { rowbuf, colbuf, boxbuf := make([][]bool, 9), make([][]bool, 9), make([][]bool, 9) for i := 0; i < 9; i++ { rowbuf[i] = make([]bool, 9) diff --git a/Algorithms/0036. Valid Sudoku/36. Valid Sudoku_test.go b/Algorithms/0036. Valid Sudoku/36. Valid Sudoku_test.go index 3003e8ee..0d4ad83b 100644 --- a/Algorithms/0036. Valid Sudoku/36. Valid Sudoku_test.go +++ b/Algorithms/0036. Valid Sudoku/36. Valid Sudoku_test.go @@ -73,7 +73,7 @@ func Test_Problem36(t *testing.T) { for _, q := range qs { _, p := q.ans36, q.para36 - fmt.Printf("【input】:%v 【output】:%v\n", p, isValidSudoku_(p.s)) + fmt.Printf("【input】:%v 【output】:%v\n", p, isValidSudoku1(p.s)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0047. Permutations II/47. Permutations II.go b/Algorithms/0047. Permutations II/47. Permutations II.go index 232f5b19..98f95535 100644 --- a/Algorithms/0047. Permutations II/47. Permutations II.go +++ b/Algorithms/0047. Permutations II/47. Permutations II.go @@ -8,11 +8,11 @@ func permuteUnique(nums []int) [][]int { } used, p, res := make([]bool, len(nums)), []int{}, [][]int{} sort.Ints(nums) // 这里是去重的关键逻辑 - generatePermutation_47(nums, 0, p, &res, &used) + generatePermutation47(nums, 0, p, &res, &used) return res } -func generatePermutation_47(nums []int, index int, p []int, res *[][]int, used *[]bool) { +func generatePermutation47(nums []int, index int, p []int, res *[][]int, used *[]bool) { if index == len(nums) { temp := make([]int, len(p)) copy(temp, p) @@ -26,7 +26,7 @@ func generatePermutation_47(nums []int, index int, p []int, res *[][]int, used * } (*used)[i] = true p = append(p, nums[i]) - generatePermutation_47(nums, index+1, p, res, used) + generatePermutation47(nums, index+1, p, res, used) p = p[:len(p)-1] (*used)[i] = false } diff --git a/Algorithms/0052. N-Queens II/52. N-Queens II.go b/Algorithms/0052. N-Queens II/52. N-Queens II.go index a4731af1..32226aa3 100644 --- a/Algorithms/0052. N-Queens II/52. N-Queens II.go +++ b/Algorithms/0052. N-Queens II/52. N-Queens II.go @@ -7,14 +7,14 @@ func totalNQueens(n int) int { } // 解法二,DFS 回溯法 -func totalNQueens_(n int) int { +func totalNQueens1(n int) int { col, dia1, dia2, row, res := make([]bool, n), make([]bool, 2*n-1), make([]bool, 2*n-1), []int{}, 0 - putQueen_(n, 0, &col, &dia1, &dia2, &row, &res) + putQueen52(n, 0, &col, &dia1, &dia2, &row, &res) return res } // 尝试在一个n皇后问题中, 摆放第index行的皇后位置 -func putQueen_(n, index int, col, dia1, dia2 *[]bool, row *[]int, res *int) { +func putQueen52(n, index int, col, dia1, dia2 *[]bool, row *[]int, res *int) { if index == n { *res++ return @@ -26,7 +26,7 @@ func putQueen_(n, index int, col, dia1, dia2 *[]bool, row *[]int, res *int) { (*col)[i] = true (*dia1)[index+i] = true (*dia2)[index-i+n-1] = true - putQueen_(n, index+1, col, dia1, dia2, row, res) + putQueen52(n, index+1, col, dia1, dia2, row, res) (*col)[i] = false (*dia1)[index+i] = false (*dia2)[index-i+n-1] = false diff --git a/Algorithms/0053. Maximum Subarray/53. Maximum Subarray.go b/Algorithms/0053. Maximum Subarray/53. Maximum Subarray.go index 80697f25..03e3e227 100644 --- a/Algorithms/0053. Maximum Subarray/53. Maximum Subarray.go +++ b/Algorithms/0053. Maximum Subarray/53. Maximum Subarray.go @@ -22,7 +22,7 @@ func maxSubArray(nums []int) int { } // 解法二 模拟 -func maxSubArray_(nums []int) int { +func maxSubArray1(nums []int) int { if len(nums) == 1 { return nums[0] } diff --git a/Algorithms/0056. Merge Intervals/56. Merge Intervals.go b/Algorithms/0056. Merge Intervals/56. Merge Intervals.go index 03226c41..4ce74167 100644 --- a/Algorithms/0056. Merge Intervals/56. Merge Intervals.go +++ b/Algorithms/0056. Merge Intervals/56. Merge Intervals.go @@ -8,12 +8,13 @@ package leetcode * } */ +// Interval define type Interval struct { Start int End int } -func merge_(intervals []Interval) []Interval { +func merge56(intervals []Interval) []Interval { if len(intervals) == 0 { return intervals } @@ -35,17 +36,15 @@ func merge_(intervals []Interval) []Interval { func max(a int, b int) int { if a > b { return a - } else { - return b } + return b } func min(a int, b int) int { if a > b { return b - } else { - return a } + return a } func partitionSort(a []Interval, lo, hi int) int { diff --git a/Algorithms/0056. Merge Intervals/56. Merge Intervals_test.go b/Algorithms/0056. Merge Intervals/56. Merge Intervals_test.go index b98f786d..30232c71 100644 --- a/Algorithms/0056. Merge Intervals/56. Merge Intervals_test.go +++ b/Algorithms/0056. Merge Intervals/56. Merge Intervals_test.go @@ -66,7 +66,7 @@ func Test_Problem56(t *testing.T) { for _, q := range qs { _, p := q.ans56, q.para56 - fmt.Printf("【input】:%v 【output】:%v\n", p, merge_(p.one)) + fmt.Printf("【input】:%v 【output】:%v\n", p, merge56(p.one)) } 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 2e7c2fb5..ab706adf 100644 --- a/Algorithms/0064. Minimum Path Sum/64. Minimum Path Sum.go +++ b/Algorithms/0064. Minimum Path Sum/64. Minimum Path Sum.go @@ -19,7 +19,7 @@ func minPathSum(grid [][]int) int { } // 解法二 最原始的方法,辅助空间 O(n^2) -func minPathSum_(grid [][]int) int { +func minPathSum1(grid [][]int) int { if len(grid) == 0 { return 0 } diff --git a/Algorithms/0069. Sqrt(x)/69. Sqrt(x).go b/Algorithms/0069. Sqrt(x)/69. Sqrt(x).go index 361ea671..c228c82d 100644 --- a/Algorithms/0069. Sqrt(x)/69. Sqrt(x).go +++ b/Algorithms/0069. Sqrt(x)/69. Sqrt(x).go @@ -21,7 +21,7 @@ func mySqrt(x int) int { } // 解法二 牛顿迭代法 https://en.wikipedia.org/wiki/Integer_square_root -func mySqrt_(x int) int { +func mySqrt1(x int) int { r := x for r*r > x { r = (r + x/r) / 2 diff --git a/Algorithms/0069. Sqrt(x)/69. Sqrt(x)_test.go b/Algorithms/0069. Sqrt(x)/69. Sqrt(x)_test.go index a16323e1..69e59cfc 100644 --- a/Algorithms/0069. Sqrt(x)/69. Sqrt(x)_test.go +++ b/Algorithms/0069. Sqrt(x)/69. Sqrt(x)_test.go @@ -41,7 +41,7 @@ func Test_Problem69(t *testing.T) { for _, q := range qs { _, p := q.ans69, q.para69 - fmt.Printf("【input】:%v 【output】:%v\n", p, mySqrt_(p.one)) + fmt.Printf("【input】:%v 【output】:%v\n", p, mySqrt1(p.one)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0071. Simplify Path/71. Simplify Path.go b/Algorithms/0071. Simplify Path/71. Simplify Path.go index 5726957f..f4c8b74e 100644 --- a/Algorithms/0071. Simplify Path/71. Simplify Path.go +++ b/Algorithms/0071. Simplify Path/71. Simplify Path.go @@ -23,13 +23,12 @@ func simplifyPath(path string) string { } if len(stack) == 0 { return "/" - } else { - res = strings.Join(stack, "/") } + res = strings.Join(stack, "/") return "/" + res } // 解法二 golang 的官方库 API -func simplifyPath_(path string) string { +func simplifyPath1(path string) string { return filepath.Clean(path) } diff --git a/Algorithms/0078. Subsets/78. Subsets.go b/Algorithms/0078. Subsets/78. Subsets.go index 92f27459..f69f541f 100644 --- a/Algorithms/0078. Subsets/78. Subsets.go +++ b/Algorithms/0078. Subsets/78. Subsets.go @@ -28,7 +28,7 @@ func generateSubsets(nums []int, k, start int, c []int, res *[][]int) { } // 解法二 -func subsets_(nums []int) [][]int { +func subsets1(nums []int) [][]int { res := make([][]int, 1) sort.Ints(nums) for i := range nums { diff --git a/Algorithms/0079. Word Search/79. Word Search.go b/Algorithms/0079. Word Search/79. Word Search.go index 2d40e845..6a6bbca5 100644 --- a/Algorithms/0079. Word Search/79. Word Search.go +++ b/Algorithms/0079. Word Search/79. Word Search.go @@ -13,7 +13,7 @@ func exist(board [][]byte, word string) bool { visited[i] = make([]bool, len(board[0])) } for i, v := range board { - for j, _ := range v { + for j := range v { if searchWord(board, visited, word, 0, i, j) { return true } diff --git a/Algorithms/0080. Remove Duplicates from Sorted Array II/80. Remove Duplicates from Sorted Array II.go b/Algorithms/0080. Remove Duplicates from Sorted Array II/80. Remove Duplicates from Sorted Array II.go index 6b7cb2ad..4b8227b0 100644 --- a/Algorithms/0080. Remove Duplicates from Sorted Array II/80. Remove Duplicates from Sorted Array II.go +++ b/Algorithms/0080. Remove Duplicates from Sorted Array II/80. Remove Duplicates from Sorted Array II.go @@ -1,6 +1,6 @@ package leetcode -func removeDuplicates_80(nums []int) int { +func removeDuplicates80(nums []int) int { if len(nums) == 0 { return 0 } @@ -22,7 +22,7 @@ func removeDuplicates_80(nums []int) int { last += 2 } else { nums[last+1] = nums[finder] - last += 1 + last++ } if finder == len(nums)-1 { if nums[finder] != nums[last-1] { diff --git a/Algorithms/0080. Remove Duplicates from Sorted Array II/80. Remove Duplicates from Sorted Array II_test.go b/Algorithms/0080. Remove Duplicates from Sorted Array II/80. Remove Duplicates from Sorted Array II_test.go index e6ed4f2c..3e2e2dce 100644 --- a/Algorithms/0080. Remove Duplicates from Sorted Array II/80. Remove Duplicates from Sorted Array II_test.go +++ b/Algorithms/0080. Remove Duplicates from Sorted Array II/80. Remove Duplicates from Sorted Array II_test.go @@ -61,7 +61,7 @@ func Test_Problem80(t *testing.T) { for _, q := range qs { _, p := q.ans80, q.para80 - fmt.Printf("【input】:%v 【output】:%v\n", p.one, removeDuplicates_80(p.one)) + fmt.Printf("【input】:%v 【output】:%v\n", p.one, removeDuplicates80(p.one)) } fmt.Printf("\n\n\n") } 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 d6a168b5..60c2cd92 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 @@ -62,8 +62,7 @@ func deleteDuplicates2(head *ListNode) *ListNode { head = head.Next } return deleteDuplicates(head.Next) - } else { - head.Next = deleteDuplicates(head.Next) } + head.Next = deleteDuplicates(head.Next) return head } diff --git a/Algorithms/0086. Partition List/86. Partition List.go b/Algorithms/0086. Partition List/86. Partition List.go index 58b745b9..4d4b40c3 100644 --- a/Algorithms/0086. Partition List/86. Partition List.go +++ b/Algorithms/0086. Partition List/86. Partition List.go @@ -30,6 +30,7 @@ func partition(head *ListNode, x int) *ListNode { return beforeHead.Next } +// DoublyListNode define type DoublyListNode struct { Val int Prev *DoublyListNode @@ -37,7 +38,7 @@ type DoublyListNode struct { } // 解法二 双链表 -func partition_(head *ListNode, x int) *ListNode { +func partition1(head *ListNode, x int) *ListNode { if head == nil || head.Next == nil { return head } diff --git a/Algorithms/0089. Gray Code/89. Gray Code.go b/Algorithms/0089. Gray Code/89. Gray Code.go index 7e431418..d975a8fe 100644 --- a/Algorithms/0089. Gray Code/89. Gray Code.go +++ b/Algorithms/0089. Gray Code/89. Gray Code.go @@ -53,7 +53,7 @@ func flipGrayCode(num int) int { } // 解法二 直译 -func grayCode_(n int) []int { +func grayCode1(n int) []int { var l uint = 1 << uint(n) out := make([]int, l) for i := uint(0); i < l; i++ { diff --git a/Algorithms/0093. Restore IP Addresses/93. Restore IP Addresses.go b/Algorithms/0093. Restore IP Addresses/93. Restore IP Addresses.go index 0254d976..5e4ce18c 100644 --- a/Algorithms/0093. Restore IP Addresses/93. Restore IP Addresses.go +++ b/Algorithms/0093. Restore IP Addresses/93. Restore IP Addresses.go @@ -4,7 +4,7 @@ import ( "strconv" ) -func restoreIpAddresses(s string) []string { +func restoreIPAddresses(s string) []string { if s == "" { return []string{} } diff --git a/Algorithms/0093. Restore IP Addresses/93. Restore IP Addresses_test.go b/Algorithms/0093. Restore IP Addresses/93. Restore IP Addresses_test.go index c3fa067d..f528a746 100644 --- a/Algorithms/0093. Restore IP Addresses/93. Restore IP Addresses_test.go +++ b/Algorithms/0093. Restore IP Addresses/93. Restore IP Addresses_test.go @@ -46,7 +46,7 @@ func Test_Problem93(t *testing.T) { for _, q := range qs { _, p := q.ans93, q.para93 - fmt.Printf("【input】:%v 【output】:%v\n", p, restoreIpAddresses(p.s)) + fmt.Printf("【input】:%v 【output】:%v\n", p, restoreIPAddresses(p.s)) } 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 b2fff870..8e626a68 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 @@ -24,7 +24,7 @@ func isValidbst(root *TreeNode, min, max float64) bool { } // 解法二,把 BST 按照左中右的顺序输出到数组中,如果是 BST,则数组中的数字是从小到大有序的,如果出现逆序就不是 BST -func isValidBST_(root *TreeNode) bool { +func isValidBST1(root *TreeNode) bool { arr := []int{} inOrder(root, &arr) for i := 1; i < len(arr); i++ { 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 caf5fca2..07ab3b1f 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 @@ -43,7 +43,7 @@ func levelOrder(root *TreeNode) [][]int { } // 解法二 DFS -func levelOrder_(root *TreeNode) [][]int { +func levelOrder1(root *TreeNode) [][]int { levels := [][]int{} dfsLevel(root, -1, &levels) return levels 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 afba4390..a5b40573 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 @@ -16,6 +16,7 @@ package leetcode * } */ +// TreeNode define type TreeNode struct { Val int Left *TreeNode 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 a080b845..f1846f8d 100644 --- a/Algorithms/0113. Path Sum II/113. Path Sum II.go +++ b/Algorithms/0113. Path Sum II/113. Path Sum II.go @@ -32,7 +32,7 @@ func findPath(n *TreeNode, sum int, slice [][]int, stack []int) [][]int { } // 解法二 -func pathSum_(root *TreeNode, sum int) [][]int { +func pathSum1(root *TreeNode, sum int) [][]int { if root == nil { return [][]int{} } 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 37460479..865988e5 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 @@ -23,7 +23,7 @@ func flatten(root *TreeNode) { } // 解法二 递归 -func flatten_1(root *TreeNode) { +func flatten1(root *TreeNode) { if root == nil || (root.Left == nil && root.Right == nil) { return } @@ -37,7 +37,9 @@ func flatten_1(root *TreeNode) { } root.Right = currRight } -func flatten_2(root *TreeNode) { + +// 解法三 递归 +func flatten2(root *TreeNode) { if root == nil { return } diff --git a/Algorithms/0120. Triangle/120. Triangle.go b/Algorithms/0120. Triangle/120. Triangle.go index c80fcd5d..83a1c47e 100644 --- a/Algorithms/0120. Triangle/120. Triangle.go +++ b/Algorithms/0120. Triangle/120. Triangle.go @@ -18,7 +18,7 @@ func minimumTotal(triangle [][]int) int { } // 解法二 正常 DP,空间复杂度 O(n) -func minimumTotal_(triangle [][]int) int { +func minimumTotal1(triangle [][]int) int { if len(triangle) == 0 { return 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 df7652b0..d0b2ca17 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 @@ -18,7 +18,7 @@ func maxProfit(prices []int) int { } // 解法二 单调栈 -func maxProfit_(prices []int) int { +func maxProfit1(prices []int) int { if len(prices) == 0 { return 0 } diff --git a/Algorithms/0122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II.go b/Algorithms/0122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II.go index 52a112fa..b93ed246 100644 --- a/Algorithms/0122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II.go +++ b/Algorithms/0122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II.go @@ -1,6 +1,6 @@ package leetcode -func maxProfit_122(prices []int) int { +func maxProfit122(prices []int) int { profit := 0 for i := 0; i < len(prices)-1; i++ { if prices[i+1] > prices[i] { diff --git a/Algorithms/0122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II_test.go b/Algorithms/0122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II_test.go index 2c63fe50..009f44c4 100644 --- a/Algorithms/0122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II_test.go +++ b/Algorithms/0122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II_test.go @@ -56,7 +56,7 @@ func Test_Problem122(t *testing.T) { for _, q := range qs { _, p := q.ans122, q.para122 - fmt.Printf("【input】:%v 【output】:%v\n", p, maxProfit_122(p.one)) + fmt.Printf("【input】:%v 【output】:%v\n", p, maxProfit122(p.one)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0126. Word Ladder II/126. Word Ladder II.go b/Algorithms/0126. Word Ladder II/126. Word Ladder II.go index 141d84c6..46cc539b 100644 --- a/Algorithms/0126. Word Ladder II/126. Word Ladder II.go +++ b/Algorithms/0126. Word Ladder II/126. Word Ladder II.go @@ -47,7 +47,7 @@ func findLadders(beginWord string, endWord string, wordList []string) [][]string if len(result) > 0 { return result } - for k, _ := range levelMap { + for k := range levelMap { delete(wordMap, k) } // clear levelMap diff --git a/Algorithms/0131. Palindrome Partitioning/131. Palindrome Partitioning.go b/Algorithms/0131. Palindrome Partitioning/131. Palindrome Partitioning.go index d5c43776..f8b39033 100644 --- a/Algorithms/0131. Palindrome Partitioning/131. Palindrome Partitioning.go +++ b/Algorithms/0131. Palindrome Partitioning/131. Palindrome Partitioning.go @@ -1,7 +1,7 @@ package leetcode // 解法一 -func partition_131(s string) [][]string { +func partition131(s string) [][]string { if s == "" { return [][]string{} } @@ -22,16 +22,16 @@ func findPalindrome(str string, index int, s string, isPal bool, pal []string, r if index == 0 { s = string(str[index]) pal = append(pal, s) - findPalindrome(str, index+1, s, isPal && isPalindrome_131(s), pal, res) + findPalindrome(str, index+1, s, isPal && isPalindrome131(s), pal, res) } else { temp := pal[len(pal)-1] s = pal[len(pal)-1] + string(str[index]) pal[len(pal)-1] = s - findPalindrome(str, index+1, s, isPalindrome_131(s), pal, res) + findPalindrome(str, index+1, s, isPalindrome131(s), pal, res) pal[len(pal)-1] = temp - if isPalindrome_131(temp) { + if isPalindrome131(temp) { pal = append(pal, string(str[index])) - findPalindrome(str, index+1, temp, isPal && isPalindrome_131(temp), pal, res) + findPalindrome(str, index+1, temp, isPal && isPalindrome131(temp), pal, res) pal = pal[:len(pal)-1] } @@ -39,7 +39,7 @@ func findPalindrome(str string, index int, s string, isPal bool, pal []string, r return } -func isPalindrome_131(s string) bool { +func isPalindrome131(s string) bool { slen := len(s) for i, j := 0, slen-1; i < j; i, j = i+1, j-1 { if s[i] != s[j] { @@ -50,18 +50,18 @@ func isPalindrome_131(s string) bool { } // 解法二 -func partition_131_2(s string) [][]string { +func partition131_1(s string) [][]string { result := [][]string{} size := len(s) if size == 0 { return result } current := make([]string, 0, size) - dfs_131(s, 0, current, &result) + dfs131(s, 0, current, &result) return result } -func dfs_131(s string, idx int, cur []string, result *[][]string) { +func dfs131(s string, idx int, cur []string, result *[][]string) { start, end := idx, len(s) if start == end { temp := make([]string, len(cur)) @@ -71,7 +71,7 @@ func dfs_131(s string, idx int, cur []string, result *[][]string) { } for i := start; i < end; i++ { if isPal(s, start, i) { - dfs_131(s, i+1, append(cur, s[start:i+1]), result) + dfs131(s, i+1, append(cur, s[start:i+1]), result) } } } diff --git a/Algorithms/0131. Palindrome Partitioning/131. Palindrome Partitioning_test.go b/Algorithms/0131. Palindrome Partitioning/131. Palindrome Partitioning_test.go index cc20e953..d482ce22 100644 --- a/Algorithms/0131. Palindrome Partitioning/131. Palindrome Partitioning_test.go +++ b/Algorithms/0131. Palindrome Partitioning/131. Palindrome Partitioning_test.go @@ -51,7 +51,7 @@ func Test_Problem131(t *testing.T) { for _, q := range qs { _, p := q.ans131, q.para131 - fmt.Printf("【input】:%v 【output】:%v\n", p, partition_131(p.s)) + fmt.Printf("【input】:%v 【output】:%v\n", p, partition131(p.s)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0137. Single Number II/137. Single Number II.go b/Algorithms/0137. Single Number II/137. Single Number II.go index d0d0ecce..72d9555e 100644 --- a/Algorithms/0137. Single Number II/137. Single Number II.go +++ b/Algorithms/0137. Single Number II/137. Single Number II.go @@ -24,7 +24,7 @@ func singleNumberIIIII(nums []int) int { } // 解法二 -func singleNumberIIIII_(nums []int) int { +func singleNumberIIIII1(nums []int) int { twos, threes, ones := 0xffffffff, 0xffffffff, 0 for i := 0; i < len(nums); i++ { threes = threes ^ (nums[i] & twos) 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 bd5f240c..9d613030 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 @@ -11,7 +11,7 @@ func detectCycle(head *ListNode) *ListNode { if head == nil || head.Next == nil { return nil } - isCycle, slow := hasCycle_(head) + isCycle, slow := hasCycle142(head) if !isCycle { return nil } @@ -23,7 +23,7 @@ func detectCycle(head *ListNode) *ListNode { return fast } -func hasCycle_(head *ListNode) (bool, *ListNode) { +func hasCycle142(head *ListNode) (bool, *ListNode) { fast := head slow := head for slow != nil && fast != nil && fast.Next != nil { diff --git a/Algorithms/0143. Reorder List/143. Reorder List.go b/Algorithms/0143. Reorder List/143. Reorder List.go index 68a31c1b..d48732c9 100644 --- a/Algorithms/0143. Reorder List/143. Reorder List.go +++ b/Algorithms/0143. Reorder List/143. Reorder List.go @@ -46,7 +46,7 @@ func reorderList(head *ListNode) *ListNode { } // 解法二 数组 -func reorderList_1(head *ListNode) *ListNode { +func reorderList1(head *ListNode) *ListNode { array := listToArray(head) length := len(array) if length == 0 { 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 ba0cc501..003ab563 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 @@ -27,7 +27,7 @@ func preorderTraversal(root *TreeNode) []int { } // 解法二 -func preorderTraversal_(root *TreeNode) []int { +func preorderTraversal1(root *TreeNode) []int { var result []int preorder(root, &result) return result diff --git a/Algorithms/0148. Sort List/148. Sort List.go b/Algorithms/0148. Sort List/148. Sort List.go index 9aff39f0..049dbb58 100644 --- a/Algorithms/0148. Sort List/148. Sort List.go +++ b/Algorithms/0148. Sort List/148. Sort List.go @@ -18,17 +18,17 @@ func sortList(head *ListNode) *ListNode { return head } - middleNode := middleNode_(head) + middleNode := middleNode1(head) cur = middleNode.Next middleNode.Next = nil middleNode = cur left := sortList(head) right := sortList(middleNode) - return mergeTwoLists_(left, right) + return mergeTwoLists148(left, right) } -func middleNode_(head *ListNode) *ListNode { +func middleNode1(head *ListNode) *ListNode { if head == nil || head.Next == nil { return head } @@ -41,7 +41,7 @@ func middleNode_(head *ListNode) *ListNode { return p1 } -func mergeTwoLists_(l1 *ListNode, l2 *ListNode) *ListNode { +func mergeTwoLists148(l1 *ListNode, l2 *ListNode) *ListNode { if l1 == nil { return l2 } @@ -51,8 +51,7 @@ func mergeTwoLists_(l1 *ListNode, l2 *ListNode) *ListNode { if l1.Val < l2.Val { l1.Next = mergeTwoLists(l1.Next, l2) return l1 - } else { - l2.Next = mergeTwoLists(l1, l2.Next) - return l2 } + l2.Next = mergeTwoLists(l1, l2.Next) + return l2 } diff --git a/Algorithms/0150. Evaluate Reverse Polish Notation/150. Evaluate Reverse Polish Notation.go b/Algorithms/0150. Evaluate Reverse Polish Notation/150. Evaluate Reverse Polish Notation.go index 33e15508..eac59410 100644 --- a/Algorithms/0150. Evaluate Reverse Polish Notation/150. Evaluate Reverse Polish Notation.go +++ b/Algorithms/0150. Evaluate Reverse Polish Notation/150. Evaluate Reverse Polish Notation.go @@ -17,28 +17,28 @@ func evalRPN(tokens []string) int { sum := stack[top-2] + stack[top-1] stack = stack[:top-2] stack = append(stack, sum) - top -= 1 + top-- } case "-": { sub := stack[top-2] - stack[top-1] stack = stack[:top-2] stack = append(stack, sub) - top -= 1 + top-- } case "*": { mul := stack[top-2] * stack[top-1] stack = stack[:top-2] stack = append(stack, mul) - top -= 1 + top-- } case "/": { div := stack[top-2] / stack[top-1] stack = stack[:top-2] stack = append(stack, div) - top -= 1 + top-- } default: { diff --git a/Algorithms/0155. Min Stack/155. Min Stack.go b/Algorithms/0155. Min Stack/155. Min Stack.go index a214a2e4..5853e0d9 100644 --- a/Algorithms/0155. Min Stack/155. Min Stack.go +++ b/Algorithms/0155. Min Stack/155. Min Stack.go @@ -1,15 +1,19 @@ package leetcode +// MinStack define type MinStack struct { elements, min []int l int } /** initialize your data structure here. */ -func Constructor_155() MinStack { + +// Constructor155 define +func Constructor155() MinStack { return MinStack{make([]int, 0), make([]int, 0), 0} } +// Push define func (this *MinStack) Push(x int) { this.elements = append(this.elements, x) if this.l == 0 { diff --git a/Algorithms/0155. Min Stack/155. Min Stack_test.go b/Algorithms/0155. Min Stack/155. Min Stack_test.go index 1f658333..38a737db 100644 --- a/Algorithms/0155. Min Stack/155. Min Stack_test.go +++ b/Algorithms/0155. Min Stack/155. Min Stack_test.go @@ -6,7 +6,7 @@ import ( ) func Test_Problem155(t *testing.T) { - obj1 := Constructor_155() + obj1 := Constructor155() obj1.Push(1) fmt.Printf("obj1 = %v\n", obj1) obj1.Push(0) @@ -15,8 +15,8 @@ func Test_Problem155(t *testing.T) { fmt.Printf("obj1 = %v\n", obj1) obj1.Pop() fmt.Printf("obj1 = %v\n", obj1) - param_3 := obj1.Top() - fmt.Printf("param_3 = %v\n", param_3) - param_4 := obj1.GetMin() - fmt.Printf("param_4 = %v\n", param_4) + param3 := obj1.Top() + fmt.Printf("param_3 = %v\n", param3) + param4 := obj1.GetMin() + fmt.Printf("param_4 = %v\n", param4) } diff --git a/Algorithms/0164. Maximum Gap/164. Maximum Gap.go b/Algorithms/0164. Maximum Gap/164. Maximum Gap.go index ceac05de..5462ddb8 100644 --- a/Algorithms/0164. Maximum Gap/164. Maximum Gap.go +++ b/Algorithms/0164. Maximum Gap/164. Maximum Gap.go @@ -5,7 +5,7 @@ func maximumGap(nums []int) int { if len(nums) < 2 { return 0 } - quickSort__(nums, 0, len(nums)-1) + quickSort164(nums, 0, len(nums)-1) res := 0 for i := 0; i < len(nums)-1; i++ { @@ -16,7 +16,7 @@ func maximumGap(nums []int) int { return res } -func partition__(a []int, lo, hi int) int { +func partition164(a []int, lo, hi int) int { pivot := a[hi] i := lo - 1 for j := lo; j < hi; j++ { @@ -28,17 +28,17 @@ func partition__(a []int, lo, hi int) int { a[i+1], a[hi] = a[hi], a[i+1] return i + 1 } -func quickSort__(a []int, lo, hi int) { +func quickSort164(a []int, lo, hi int) { if lo >= hi { return } - p := partition__(a, lo, hi) - quickSort__(a, lo, p-1) - quickSort__(a, p+1, hi) + p := partition164(a, lo, hi) + quickSort164(a, lo, p-1) + quickSort164(a, p+1, hi) } // 解法二 -func maximumGap_(nums []int) int { +func maximumGap1(nums []int) int { if nums == nil || len(nums) < 2 { return 0 diff --git a/Algorithms/0164. Maximum Gap/164. Maximum Gap_test.go b/Algorithms/0164. Maximum Gap/164. Maximum Gap_test.go index cb323f71..cb203d87 100644 --- a/Algorithms/0164. Maximum Gap/164. Maximum Gap_test.go +++ b/Algorithms/0164. Maximum Gap/164. Maximum Gap_test.go @@ -55,7 +55,7 @@ func Test_Problem164(t *testing.T) { for _, q := range qs { _, p := q.ans164, q.para164 - fmt.Printf("【input】:%v 【output】:%v\n", p, maximumGap_(p.one)) + fmt.Printf("【input】:%v 【output】:%v\n", p, maximumGap1(p.one)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0167. Two Sum II - Input array is sorted/167. Two Sum II - Input array is sorted.go b/Algorithms/0167. Two Sum II - Input array is sorted/167. Two Sum II - Input array is sorted.go index 17a289f8..b73a32e1 100644 --- a/Algorithms/0167. Two Sum II - Input array is sorted/167. Two Sum II - Input array is sorted.go +++ b/Algorithms/0167. Two Sum II - Input array is sorted/167. Two Sum II - Input array is sorted.go @@ -1,7 +1,7 @@ package leetcode // 解法一 这一题可以利用数组有序的特性 -func twoSum_(numbers []int, target int) []int { +func twoSum167(numbers []int, target int) []int { i, j := 0, len(numbers)-1 for i < j { if numbers[i]+numbers[j] == target { @@ -16,7 +16,7 @@ func twoSum_(numbers []int, target int) []int { } // 解法二 不管数组是否有序,空间复杂度比上一种解法要多 O(n) -func twoSum__(numbers []int, target int) []int { +func twoSum167_1(numbers []int, target int) []int { m := make(map[int]int) for i := 0; i < len(numbers); i++ { another := target - numbers[i] diff --git a/Algorithms/0167. Two Sum II - Input array is sorted/167. Two Sum II - Input array is sorted_test.go b/Algorithms/0167. Two Sum II - Input array is sorted/167. Two Sum II - Input array is sorted_test.go index fde71471..e7336806 100644 --- a/Algorithms/0167. Two Sum II - Input array is sorted/167. Two Sum II - Input array is sorted_test.go +++ b/Algorithms/0167. Two Sum II - Input array is sorted/167. Two Sum II - Input array is sorted_test.go @@ -37,7 +37,7 @@ func Test_Problem167(t *testing.T) { for _, q := range qs { _, p := q.ans167, q.para167 - fmt.Printf("【input】:%v 【output】:%v\n", p.one, twoSum_(p.one, p.two)) + fmt.Printf("【input】:%v 【output】:%v\n", p.one, twoSum167(p.one, p.two)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0169. Majority Element/169. Majority Element.go b/Algorithms/0169. Majority Element/169. Majority Element.go index b344af09..fed696f0 100644 --- a/Algorithms/0169. Majority Element/169. Majority Element.go +++ b/Algorithms/0169. Majority Element/169. Majority Element.go @@ -18,7 +18,7 @@ func majorityElement(nums []int) int { } // 解法二 时间复杂度 O(n) 空间复杂度 O(n) -func majorityElement_(nums []int) int { +func majorityElement1(nums []int) int { m := make(map[int]int) for _, v := range nums { m[v]++ 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 050788e2..c7986e35 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 @@ -10,12 +10,15 @@ import "container/heap" * Right *TreeNode * } */ + +// BSTIterator define type BSTIterator struct { pq PriorityQueueOfInt count int } -func Constructor_173(root *TreeNode) BSTIterator { +// Constructor173 define +func Constructor173(root *TreeNode) BSTIterator { result, pq := []int{}, PriorityQueueOfInt{} postorder(root, &result) for _, v := range result { 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 559b4f1b..6de0e627 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 @@ -8,20 +8,20 @@ import ( func Test_Problem173(t *testing.T) { root := Ints2TreeNode([]int{9, 7, 15, 3, NULL, NULL, 20}) - obj := Constructor_173(root) + obj := Constructor173(root) fmt.Printf("obj = %v\n", obj) - param_1 := obj.Next() - fmt.Printf("param_1 = %v\n", param_1) - param_2 := obj.HasNext() - fmt.Printf("param_2 = %v\n", param_2) - param_1 = obj.Next() - fmt.Printf("param_1 = %v\n", param_1) - param_1 = obj.Next() - fmt.Printf("param_1 = %v\n", param_1) - param_1 = obj.Next() - fmt.Printf("param_1 = %v\n", param_1) - param_1 = obj.Next() - fmt.Printf("param_1 = %v\n", param_1) - param_2 = obj.HasNext() - fmt.Printf("param_2 = %v\n", param_2) + param1 := obj.Next() + fmt.Printf("param_1 = %v\n", param1) + param2 := obj.HasNext() + fmt.Printf("param_2 = %v\n", param2) + param1 = obj.Next() + fmt.Printf("param_1 = %v\n", param1) + param1 = obj.Next() + fmt.Printf("param_1 = %v\n", param1) + param1 = obj.Next() + fmt.Printf("param_1 = %v\n", param1) + param1 = obj.Next() + fmt.Printf("param_1 = %v\n", param1) + param2 = obj.HasNext() + fmt.Printf("param_2 = %v\n", param2) } diff --git a/Algorithms/0187. Repeated DNA Sequences/187. Repeated DNA Sequences.go b/Algorithms/0187. Repeated DNA Sequences/187. Repeated DNA Sequences.go index 2ab4a09f..a2a74f8b 100644 --- a/Algorithms/0187. Repeated DNA Sequences/187. Repeated DNA Sequences.go +++ b/Algorithms/0187. Repeated DNA Sequences/187. Repeated DNA Sequences.go @@ -23,7 +23,7 @@ func findRepeatedDnaSequences(s string) []string { } // 解法二 -func findRepeatedDnaSequences_(s string) []string { +func findRepeatedDnaSequences1(s string) []string { if len(s) < 10 { return []string{} } @@ -33,7 +33,7 @@ func findRepeatedDnaSequences_(s string) []string { if cache[curr] == 1 { ans = append(ans, curr) } - cache[curr] += 1 + cache[curr]++ } return ans } diff --git a/Algorithms/0190. Reverse Bits/190. Reverse Bits.go b/Algorithms/0190. Reverse Bits/190. Reverse Bits.go index 2a548071..cde28878 100644 --- a/Algorithms/0190. Reverse Bits/190. Reverse Bits.go +++ b/Algorithms/0190. Reverse Bits/190. Reverse Bits.go @@ -1,7 +1,7 @@ package leetcode func reverseBits(num uint32) uint32 { - var res uint32 = 0 + var res uint32 for i := 0; i < 32; i++ { res = res<<1 | num&1 num >>= 1 diff --git a/Algorithms/0198. House Robber/198. House Robber.go b/Algorithms/0198. House Robber/198. House Robber.go index e7456055..b8a82fca 100644 --- a/Algorithms/0198. House Robber/198. House Robber.go +++ b/Algorithms/0198. House Robber/198. House Robber.go @@ -1,7 +1,7 @@ package leetcode // 解法一 DP -func rob_(nums []int) int { +func rob198(nums []int) int { n := len(nums) if n == 0 { return 0 @@ -19,7 +19,7 @@ func rob_(nums []int) int { } // 解法二 DP 优化辅助空间,把迭代的值保存在 2 个变量中 -func rob__(nums []int) int { +func rob198_1(nums []int) int { n := len(nums) if n == 0 { return 0 diff --git a/Algorithms/0198. House Robber/198. House Robber_test.go b/Algorithms/0198. House Robber/198. House Robber_test.go index 40d35156..e2f9be99 100644 --- a/Algorithms/0198. House Robber/198. House Robber_test.go +++ b/Algorithms/0198. House Robber/198. House Robber_test.go @@ -45,7 +45,7 @@ func Test_Problem198(t *testing.T) { for _, q := range qs { _, p := q.ans198, q.para198 - fmt.Printf("【input】:%v 【output】:%v\n", p, rob_(p.one)) + fmt.Printf("【input】:%v 【output】:%v\n", p, rob198(p.one)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0201. Bitwise AND of Numbers Range/201. Bitwise AND of Numbers Range.go b/Algorithms/0201. Bitwise AND of Numbers Range/201. Bitwise AND of Numbers Range.go index 177ee2df..3e6e5076 100644 --- a/Algorithms/0201. Bitwise AND of Numbers Range/201. Bitwise AND of Numbers Range.go +++ b/Algorithms/0201. Bitwise AND of Numbers Range/201. Bitwise AND of Numbers Range.go @@ -1,7 +1,7 @@ package leetcode // 解法一 -func rangeBitwiseAnd_(m int, n int) int { +func rangeBitwiseAnd1(m int, n int) int { if m == 0 { return 0 } diff --git a/Algorithms/0202. Happy Number/202. Happy Number.go b/Algorithms/0202. Happy Number/202. Happy Number.go index adf6a0cd..3764600e 100644 --- a/Algorithms/0202. Happy Number/202. Happy Number.go +++ b/Algorithms/0202. Happy Number/202. Happy Number.go @@ -15,12 +15,11 @@ func isHappy(n int) bool { if _, ok := record[res]; !ok { if res == 1 { return true - } else { - record[res] = res - num = res - res = 0 - continue } + record[res] = res + num = res + res = 0 + continue } else { return false } diff --git a/Algorithms/0208. Implement Trie (Prefix Tree)/208. Implement Trie (Prefix Tree).go b/Algorithms/0208. Implement Trie (Prefix Tree)/208. Implement Trie (Prefix Tree).go index 1e727889..b9065122 100644 --- a/Algorithms/0208. Implement Trie (Prefix Tree)/208. Implement Trie (Prefix Tree).go +++ b/Algorithms/0208. Implement Trie (Prefix Tree)/208. Implement Trie (Prefix Tree).go @@ -6,7 +6,7 @@ type Trie struct { } /** Initialize your data structure here. */ -func Constructor_208() Trie { +func Constructor208() Trie { return Trie{isWord: false, children: make(map[rune]*Trie)} } diff --git a/Algorithms/0208. Implement Trie (Prefix Tree)/208. Implement Trie (Prefix Tree)_test.go b/Algorithms/0208. Implement Trie (Prefix Tree)/208. Implement Trie (Prefix Tree)_test.go index 46f1fba3..a8e150c7 100644 --- a/Algorithms/0208. Implement Trie (Prefix Tree)/208. Implement Trie (Prefix Tree)_test.go +++ b/Algorithms/0208. Implement Trie (Prefix Tree)/208. Implement Trie (Prefix Tree)_test.go @@ -6,18 +6,18 @@ import ( ) func Test_Problem208(t *testing.T) { - obj := Constructor_208() + obj := Constructor208() fmt.Printf("obj = %v\n", obj) obj.Insert("apple") fmt.Printf("obj = %v\n", obj) - param_1 := obj.Search("apple") - fmt.Printf("param_1 = %v obj = %v\n", param_1, obj) - param_2 := obj.Search("app") - fmt.Printf("param_2 = %v obj = %v\n", param_2, obj) - param_3 := obj.StartsWith("app") - fmt.Printf("param_3 = %v obj = %v\n", param_3, obj) + param1 := obj.Search("apple") + fmt.Printf("param_1 = %v obj = %v\n", param1, obj) + param2 := obj.Search("app") + fmt.Printf("param_2 = %v obj = %v\n", param2, obj) + param3 := obj.StartsWith("app") + fmt.Printf("param_3 = %v obj = %v\n", param3, obj) obj.Insert("app") fmt.Printf("obj = %v\n", obj) - param_4 := obj.Search("app") - fmt.Printf("param_4 = %v obj = %v\n", param_4, obj) + param4 := obj.Search("app") + fmt.Printf("param_4 = %v obj = %v\n", param4, obj) } diff --git a/Algorithms/0211. Add and Search Word - Data structure design/211. Add and Search Word - Data structure design.go b/Algorithms/0211. Add and Search Word - Data structure design/211. Add and Search Word - Data structure design.go index a18e6dfe..8ddaaa93 100644 --- a/Algorithms/0211. Add and Search Word - Data structure design/211. Add and Search Word - Data structure design.go +++ b/Algorithms/0211. Add and Search Word - Data structure design/211. Add and Search Word - Data structure design.go @@ -6,7 +6,7 @@ type WordDictionary struct { } /** Initialize your data structure here. */ -func Constructor_211() WordDictionary { +func Constructor211() WordDictionary { return WordDictionary{children: make(map[rune]*WordDictionary)} } diff --git a/Algorithms/0211. Add and Search Word - Data structure design/211. Add and Search Word - Data structure design_test.go b/Algorithms/0211. Add and Search Word - Data structure design/211. Add and Search Word - Data structure design_test.go index 9a222321..6dcd94b0 100644 --- a/Algorithms/0211. Add and Search Word - Data structure design/211. Add and Search Word - Data structure design_test.go +++ b/Algorithms/0211. Add and Search Word - Data structure design/211. Add and Search Word - Data structure design_test.go @@ -6,7 +6,7 @@ import ( ) func Test_Problem211(t *testing.T) { - obj := Constructor_211() + obj := Constructor211() fmt.Printf("obj = %v\n", obj) obj.AddWord("bad") fmt.Printf("obj = %v\n", obj) @@ -15,12 +15,12 @@ func Test_Problem211(t *testing.T) { obj.AddWord("mad") fmt.Printf("obj = %v\n", obj) - param_1 := obj.Search("pad") - fmt.Printf("param_1 = %v obj = %v\n", param_1, obj) - param_2 := obj.Search("bad") - fmt.Printf("param_2 = %v obj = %v\n", param_2, obj) - param_3 := obj.Search(".ad") - fmt.Printf("param_3 = %v obj = %v\n", param_3, obj) - param_4 := obj.Search("b..") - fmt.Printf("param_4 = %v obj = %v\n", param_4, obj) + param1 := obj.Search("pad") + fmt.Printf("param_1 = %v obj = %v\n", param1, obj) + param2 := obj.Search("bad") + fmt.Printf("param_2 = %v obj = %v\n", param2, obj) + param3 := obj.Search(".ad") + fmt.Printf("param_3 = %v obj = %v\n", param3, obj) + param4 := obj.Search("b..") + fmt.Printf("param_4 = %v obj = %v\n", param4, obj) } 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 1c21078d..fe1bf32d 100644 --- a/Algorithms/0213. House Robber II/213. House Robber II.go +++ b/Algorithms/0213. House Robber II/213. House Robber II.go @@ -1,6 +1,6 @@ package leetcode -func rob_213(nums []int) int { +func rob213(nums []int) int { n := len(nums) if n == 0 { return 0 @@ -12,10 +12,10 @@ func rob_213(nums []int) int { return max(nums[0], nums[1]) } // 由于首尾是相邻的,所以需要对比 [0,n-1]、[1,n] 这两个区间的最大值 - return max(rob_213_(nums, 0, n-2), rob_213_(nums, 1, n-1)) + return max(rob213_1(nums, 0, n-2), rob213_1(nums, 1, n-1)) } -func rob_213_(nums []int, start, end int) int { +func rob213_1(nums []int, start, end int) int { preMax := nums[start] curMax := max(preMax, nums[start+1]) for i := start + 2; i <= end; i++ { diff --git a/Algorithms/0213. House Robber II/213. House Robber II_test.go b/Algorithms/0213. House Robber II/213. House Robber II_test.go index 5f729e4e..c2faf927 100644 --- a/Algorithms/0213. House Robber II/213. House Robber II_test.go +++ b/Algorithms/0213. House Robber II/213. House Robber II_test.go @@ -45,7 +45,7 @@ func Test_Problem213(t *testing.T) { for _, q := range qs { _, p := q.ans213, q.para213 - fmt.Printf("【input】:%v 【output】:%v\n", p, rob_213(p.one)) + fmt.Printf("【input】:%v 【output】:%v\n", p, rob213(p.one)) } fmt.Printf("\n\n\n") } 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 236dc5eb..3f7015ff 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 @@ -3,7 +3,7 @@ package leetcode import "sort" // 解法一 排序,排序的方法反而速度是最快的 -func findKthLargest_(nums []int, k int) int { +func findKthLargest1(nums []int, k int) int { sort.Ints(nums) return nums[len(nums)-k] } @@ -17,13 +17,10 @@ func findKthLargest(nums []int, k int) int { } func selection(arr []int, l, r, k int) int { - if l == r { return arr[l] } - - p := partition__(arr, l, r) - + p := partition164(arr, l, r) if k == p { return arr[p] } else if k < p { diff --git a/Algorithms/0215. Kth Largest Element in an Array/215. Kth Largest Element in an Array_test.go b/Algorithms/0215. Kth Largest Element in an Array/215. Kth Largest Element in an Array_test.go index fe06c631..e66bb953 100644 --- a/Algorithms/0215. Kth Largest Element in an Array/215. Kth Largest Element in an Array_test.go +++ b/Algorithms/0215. Kth Largest Element in an Array/215. Kth Largest Element in an Array_test.go @@ -49,7 +49,7 @@ func Test_Problem215(t *testing.T) { question215{ para215{[]int{3, 2, 3, 1, 2, 4, 5, 5, 6, 7, 7, 8, 2, 3, 1, 1, 1, 10, 11, 5, 6, 2, 4, 7, 8, 5, 6}, 20}, - ans215{10}, + ans215{2}, }, } diff --git a/Algorithms/0224. Basic Calculator/224. Basic Calculator.go b/Algorithms/0224. Basic Calculator/224. Basic Calculator.go index e526f168..5c1f8d6f 100644 --- a/Algorithms/0224. Basic Calculator/224. Basic Calculator.go +++ b/Algorithms/0224. Basic Calculator/224. Basic Calculator.go @@ -41,7 +41,7 @@ func calculate(s string) int { } // 解法二 -func calculate_(s string) int { +func calculate1(s string) int { stack := []byte{} for i := 0; i < len(s); i++ { if s[i] == ' ' { diff --git a/Algorithms/0225. Implement Stack using Queues/225. Implement Stack using Queues.go b/Algorithms/0225. Implement Stack using Queues/225. Implement Stack using Queues.go index 92329f73..7d9e2b5e 100644 --- a/Algorithms/0225. Implement Stack using Queues/225. Implement Stack using Queues.go +++ b/Algorithms/0225. Implement Stack using Queues/225. Implement Stack using Queues.go @@ -6,7 +6,7 @@ type MyStack struct { } /** Initialize your data structure here. */ -func Constructor_225() MyStack { +func Constructor225() MyStack { return MyStack{[]int{}, []int{}} } diff --git a/Algorithms/0225. Implement Stack using Queues/225. Implement Stack using Queues_test.go b/Algorithms/0225. Implement Stack using Queues/225. Implement Stack using Queues_test.go index 7985ea82..2bcc817f 100644 --- a/Algorithms/0225. Implement Stack using Queues/225. Implement Stack using Queues_test.go +++ b/Algorithms/0225. Implement Stack using Queues/225. Implement Stack using Queues_test.go @@ -6,18 +6,18 @@ import ( ) func Test_Problem225(t *testing.T) { - obj := Constructor_225() + obj := Constructor225() fmt.Printf("obj = %v\n", obj) - param_5 := obj.Empty() - fmt.Printf("param_5 = %v\n", param_5) + param5 := obj.Empty() + fmt.Printf("param_5 = %v\n", param5) obj.Push(2) fmt.Printf("obj = %v\n", obj) obj.Push(10) fmt.Printf("obj = %v\n", obj) - param_2 := obj.Pop() - fmt.Printf("param_2 = %v\n", param_2) - param_3 := obj.Top() - fmt.Printf("param_3 = %v\n", param_3) - param_4 := obj.Empty() - fmt.Printf("param_4 = %v\n", param_4) + param2 := obj.Pop() + fmt.Printf("param_2 = %v\n", param2) + param3 := obj.Top() + fmt.Printf("param_3 = %v\n", param3) + param4 := obj.Empty() + fmt.Printf("param_4 = %v\n", param4) } diff --git a/Algorithms/0229. Majority Element II/229. Majority Element II.go b/Algorithms/0229. Majority Element II/229. Majority Element II.go index 1111bd54..17d1053d 100644 --- a/Algorithms/0229. Majority Element II/229. Majority Element II.go +++ b/Algorithms/0229. Majority Element II/229. Majority Element II.go @@ -1,7 +1,7 @@ package leetcode // 解法一 时间复杂度 O(n) 空间复杂度 O(1) -func majorityElement_229(nums []int) []int { +func majorityElement229(nums []int) []int { // since we are checking if a num appears more than 1/3 of the time // it is only possible to have at most 2 nums (>1/3 + >1/3 = >2/3) count1, count2, candidate1, candidate2 := 0, 0, 0, 1 @@ -46,7 +46,7 @@ func majorityElement_229(nums []int) []int { } // 解法二 时间复杂度 O(n) 空间复杂度 O(n) -func majorityElement_229_(nums []int) []int { +func majorityElement229_1(nums []int) []int { result, m := make([]int, 0), make(map[int]int) for _, val := range nums { if v, ok := m[val]; ok { diff --git a/Algorithms/0229. Majority Element II/229. Majority Element II_test.go b/Algorithms/0229. Majority Element II/229. Majority Element II_test.go index b7ec2762..2eb99c51 100644 --- a/Algorithms/0229. Majority Element II/229. Majority Element II_test.go +++ b/Algorithms/0229. Majority Element II/229. Majority Element II_test.go @@ -41,7 +41,7 @@ func Test_Problem229(t *testing.T) { for _, q := range qs { _, p := q.ans229, q.para229 - fmt.Printf("【input】:%v 【output】:%v\n", p, majorityElement_229(p.s)) + fmt.Printf("【input】:%v 【output】:%v\n", p, majorityElement229(p.s)) } 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 6923a8d4..f50f8845 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 @@ -10,18 +10,18 @@ package leetcode */ func kthSmallest(root *TreeNode, k int) int { res, count := 0, 0 - inorder_(root, k, &count, &res) + inorder230(root, k, &count, &res) return res } -func inorder_(node *TreeNode, k int, count *int, ans *int) { +func inorder230(node *TreeNode, k int, count *int, ans *int) { if node != nil { - inorder_(node.Left, k, count, ans) + inorder230(node.Left, k, count, ans) *count++ if *count == k { *ans = node.Val return } - inorder_(node.Right, k, count, ans) + inorder230(node.Right, k, count, ans) } } diff --git a/Algorithms/0231. Power of Two/231. Power of Two.go b/Algorithms/0231. Power of Two/231. Power of Two.go index 8a7aff06..7db41f1d 100644 --- a/Algorithms/0231. Power of Two/231. Power of Two.go +++ b/Algorithms/0231. Power of Two/231. Power of Two.go @@ -6,19 +6,19 @@ func isPowerOfTwo(num int) bool { } // 解法二 数论 -func isPowerOfTwo_1(num int) bool { +func isPowerOfTwo1(num int) bool { return num > 0 && (1073741824%num == 0) } // 解法三 打表法 -func isPowerOfTwo_2(num int) bool { +func isPowerOfTwo2(num int) bool { allPowerOfTwoMap := map[int]int{1: 1, 2: 2, 4: 4, 8: 8, 16: 16, 32: 32, 64: 64, 128: 128, 256: 256, 512: 512, 1024: 1024, 2048: 2048, 4096: 4096, 8192: 8192, 16384: 16384, 32768: 32768, 65536: 65536, 131072: 131072, 262144: 262144, 524288: 524288, 1048576: 1048576, 2097152: 2097152, 4194304: 4194304, 8388608: 8388608, 16777216: 16777216, 33554432: 33554432, 67108864: 67108864, 134217728: 134217728, 268435456: 268435456, 536870912: 536870912, 1073741824: 1073741824} _, ok := allPowerOfTwoMap[num] return ok } // 解法四 循环 -func isPowerOfTwo_3(num int) bool { +func isPowerOfTwo3(num int) bool { for num >= 2 { if num%2 == 0 { num = num / 2 diff --git a/Algorithms/0232. Implement Queue using Stacks/232. Implement Queue using Stacks.go b/Algorithms/0232. Implement Queue using Stacks/232. Implement Queue using Stacks.go index 22eaed4e..23bf3114 100644 --- a/Algorithms/0232. Implement Queue using Stacks/232. Implement Queue using Stacks.go +++ b/Algorithms/0232. Implement Queue using Stacks/232. Implement Queue using Stacks.go @@ -6,7 +6,7 @@ type MyQueue struct { } /** Initialize your data structure here. */ -func Constructor_232() MyQueue { +func Constructor232() MyQueue { tmp1, tmp2 := []int{}, []int{} return MyQueue{Stack: &tmp1, Queue: &tmp2} } diff --git a/Algorithms/0232. Implement Queue using Stacks/232. Implement Queue using Stacks_test.go b/Algorithms/0232. Implement Queue using Stacks/232. Implement Queue using Stacks_test.go index e9404ff3..ec9d672d 100644 --- a/Algorithms/0232. Implement Queue using Stacks/232. Implement Queue using Stacks_test.go +++ b/Algorithms/0232. Implement Queue using Stacks/232. Implement Queue using Stacks_test.go @@ -6,16 +6,16 @@ import ( ) func Test_Problem232(t *testing.T) { - obj := Constructor_232() + obj := Constructor232() fmt.Printf("obj = %v\n", obj) obj.Push(2) fmt.Printf("obj = %v\n", obj) obj.Push(10) fmt.Printf("obj = %v\n", obj) - param_2 := obj.Pop() - fmt.Printf("param_2 = %v\n", param_2) - param_3 := obj.Peek() - fmt.Printf("param_3 = %v\n", param_3) - param_4 := obj.Empty() - fmt.Printf("param_4 = %v\n", param_4) + param2 := obj.Pop() + fmt.Printf("param_2 = %v\n", param2) + param3 := obj.Peek() + fmt.Printf("param_3 = %v\n", param3) + param4 := obj.Empty() + fmt.Printf("param_4 = %v\n", param4) } 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 d31e752e..b0d06e2d 100644 --- a/Algorithms/0234. Palindrome Linked List/234. Palindrome Linked List.go +++ b/Algorithms/0234. Palindrome Linked List/234. Palindrome Linked List.go @@ -9,7 +9,7 @@ package leetcode */ // 此题和 143 题 Reorder List 思路基本一致 -func isPalindrome_(head *ListNode) bool { +func isPalindrome234(head *ListNode) bool { if head == nil || head.Next == nil { return true } @@ -56,6 +56,7 @@ func isPalindrome_(head *ListNode) bool { return res } +// L2ss define func L2ss(head *ListNode) []int { res := []int{} 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 30888d17..7995be3b 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 @@ -81,7 +81,7 @@ func Test_Problem234(t *testing.T) { for _, q := range qs { _, p := q.ans234, q.para234 - fmt.Printf("【input】:%v 【output】:%v\n", p, isPalindrome_(S2l(p.one))) + fmt.Printf("【input】:%v 【output】:%v\n", p, isPalindrome234(S2l(p.one))) } 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 911113f1..6f5028d0 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 @@ -8,12 +8,12 @@ package leetcode * Right *ListNode * } */ -func lowestCommonAncestor_(root, p, q *TreeNode) *TreeNode { +func lowestCommonAncestor236(root, p, q *TreeNode) *TreeNode { if root == nil || root == q || root == p { return root } - left := lowestCommonAncestor_(root.Left, p, q) - right := lowestCommonAncestor_(root.Right, p, q) + left := lowestCommonAncestor236(root.Left, p, q) + right := lowestCommonAncestor236(root.Right, p, q) if left != nil { if right != nil { 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 7830a195..5561ef4b 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 @@ -62,7 +62,7 @@ func Test_Problem236(t *testing.T) { rootOne := Ints2TreeNode(p.one) rootTwo := Ints2TreeNode(p.two) rootThr := Ints2TreeNode(p.thr) - fmt.Printf("【output】:%v \n", lowestCommonAncestor_(rootOne, rootTwo, rootThr)) + fmt.Printf("【output】:%v \n", lowestCommonAncestor236(rootOne, rootTwo, rootThr)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0239. Sliding Window Maximum/239. Sliding Window Maximum.go b/Algorithms/0239. Sliding Window Maximum/239. Sliding Window Maximum.go index 268bc412..5b0425eb 100644 --- a/Algorithms/0239. Sliding Window Maximum/239. Sliding Window Maximum.go +++ b/Algorithms/0239. Sliding Window Maximum/239. Sliding Window Maximum.go @@ -1,7 +1,7 @@ package leetcode -// 解法一 暴力解法 O(nk): -func maxSlidingWindow_(a []int, k int) []int { +// 解法一 暴力解法 O(nk) +func maxSlidingWindow1(a []int, k int) []int { res := make([]int, 0, k) n := len(a) if n == 0 { diff --git a/Algorithms/0242. Valid Anagram/242. Valid Anagram.go b/Algorithms/0242. Valid Anagram/242. Valid Anagram.go index 0531f39c..81920dd7 100644 --- a/Algorithms/0242. Valid Anagram/242. Valid Anagram.go +++ b/Algorithms/0242. Valid Anagram/242. Valid Anagram.go @@ -23,7 +23,7 @@ func isAnagram(s string, t string) bool { } // 解法二 -func isAnagram_(s string, t string) bool { +func isAnagram1(s string, t string) bool { if s == "" && t == "" { return true } diff --git a/Algorithms/0274. H-Index/274. H-Index.go b/Algorithms/0274. H-Index/274. H-Index.go index 35e59317..9d59c9db 100644 --- a/Algorithms/0274. H-Index/274. H-Index.go +++ b/Algorithms/0274. H-Index/274. H-Index.go @@ -22,8 +22,8 @@ func hIndex(citations []int) int { } // 解法二 -func hIndex_(citations []int) int { - quickSort__(citations, 0, len(citations)-1) +func hIndex1(citations []int) int { + quickSort164(citations, 0, len(citations)-1) hIndex := 0 for i := len(citations) - 1; i >= 0; i-- { if citations[i] >= len(citations)-i { diff --git a/Algorithms/0287. Find the Duplicate Number/287. Find the Duplicate Number.go b/Algorithms/0287. Find the Duplicate Number/287. Find the Duplicate Number.go index d7cdb98e..23a202d0 100644 --- a/Algorithms/0287. Find the Duplicate Number/287. Find the Duplicate Number.go +++ b/Algorithms/0287. Find the Duplicate Number/287. Find the Duplicate Number.go @@ -19,7 +19,7 @@ func findDuplicate(nums []int) int { } // 解法二 -func findDuplicate_(nums []int) int { +func findDuplicate1(nums []int) int { if len(nums) == 0 { return 0 } 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 06c06099..a0e1eb32 100644 --- a/Algorithms/0300. Longest Increasing Subsequence/300. Longest Increasing Subsequence.go +++ b/Algorithms/0300. Longest Increasing Subsequence/300. Longest Increasing Subsequence.go @@ -19,7 +19,7 @@ func lengthOfLIS(nums []int) int { } // 解法二 O(n log n) DP -func lengthOfLIS_(nums []int) int { +func lengthOfLIS1(nums []int) int { dp := []int{} for _, num := range nums { i := sort.SearchInts(dp, num) diff --git a/Algorithms/0306. Additive Number/306. Additive Number.go b/Algorithms/0306. Additive Number/306. Additive Number.go index 2be67d7d..9aac8ee5 100644 --- a/Algorithms/0306. Additive Number/306. Additive Number.go +++ b/Algorithms/0306. Additive Number/306. Additive Number.go @@ -35,7 +35,6 @@ func recursiveCheck(num string, x1 int, x2 int, left int) bool { } if strings.HasPrefix(num[left:], strconv.Itoa(x1+x2)) { return recursiveCheck(num, x2, x1+x2, left+len(strconv.Itoa(x1+x2))) - } else { - return false } + return false } 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 7990cc4f..5e2c02f4 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 @@ -5,12 +5,12 @@ import ( ) // 解法一 DP -func maxProfit_309(prices []int) int { +func maxProfit309(prices []int) int { if len(prices) <= 1 { return 0 } buy, sell := make([]int, len(prices)), make([]int, len(prices)) - for i, _ := range buy { + for i := range buy { buy[i] = math.MinInt64 } buy[0] = -prices[0] @@ -24,7 +24,7 @@ func maxProfit_309(prices []int) int { } // 解法二 优化辅助空间的 DP -func maxProfit_309_(prices []int) int { +func maxProfit309_1(prices []int) int { if len(prices) <= 1 { return 0 } diff --git a/Algorithms/0309. Best Time to Buy and Sell Stock with Cooldown/309. Best Time to Buy and Sell Stock with Cooldown_test.go b/Algorithms/0309. Best Time to Buy and Sell Stock with Cooldown/309. Best Time to Buy and Sell Stock with Cooldown_test.go index 4e3f7035..ed8a0418 100644 --- a/Algorithms/0309. Best Time to Buy and Sell Stock with Cooldown/309. Best Time to Buy and Sell Stock with Cooldown_test.go +++ b/Algorithms/0309. Best Time to Buy and Sell Stock with Cooldown/309. Best Time to Buy and Sell Stock with Cooldown_test.go @@ -61,7 +61,7 @@ func Test_Problem309(t *testing.T) { for _, q := range qs { _, p := q.ans309, q.para309 - fmt.Printf("【input】:%v 【output】:%v\n", p, maxProfit_309(p.one)) + fmt.Printf("【input】:%v 【output】:%v\n", p, maxProfit309(p.one)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0324. Wiggle Sort II/324. Wiggle Sort II.go b/Algorithms/0324. Wiggle Sort II/324. Wiggle Sort II.go index c0c3dc85..bdc08bc9 100644 --- a/Algorithms/0324. Wiggle Sort II/324. Wiggle Sort II.go +++ b/Algorithms/0324. Wiggle Sort II/324. Wiggle Sort II.go @@ -9,7 +9,7 @@ func wiggleSort(nums []int) { if len(nums) < 2 { return } - median := findKthLargest_324(nums, (len(nums)+1)/2) + median := findKthLargest324(nums, (len(nums)+1)/2) n, i, left, right := len(nums), 0, 0, len(nums)-1 for i <= right { @@ -30,29 +30,29 @@ func indexMap(index, n int) int { return (1 + 2*index) % (n | 1) } -func findKthLargest_324(nums []int, k int) int { +func findKthLargest324(nums []int, k int) int { if len(nums) == 0 { return 0 } - return selection_324(nums, 0, len(nums)-1, len(nums)-k) + return selection324(nums, 0, len(nums)-1, len(nums)-k) } -func selection_324(arr []int, l, r, k int) int { +func selection324(arr []int, l, r, k int) int { if l == r { return arr[l] } - p := partition__324(arr, l, r) + p := partition324(arr, l, r) if k == p { return arr[p] } else if k < p { - return selection_324(arr, l, p-1, k) + return selection324(arr, l, p-1, k) } else { - return selection_324(arr, p+1, r, k) + return selection324(arr, p+1, r, k) } } -func partition__324(a []int, lo, hi int) int { +func partition324(a []int, lo, hi int) int { pivot := a[hi] i := lo - 1 for j := lo; j < hi; j++ { @@ -66,7 +66,7 @@ func partition__324(a []int, lo, hi int) int { } // 解法二 -func wiggleSort_(nums []int) { +func wiggleSort1(nums []int) { if len(nums) < 2 { return } diff --git a/Algorithms/0326. Power of Three/326. Power of Three.go b/Algorithms/0326. Power of Three/326. Power of Three.go index 96a10d07..5dad4ad8 100644 --- a/Algorithms/0326. Power of Three/326. Power of Three.go +++ b/Algorithms/0326. Power of Three/326. Power of Three.go @@ -7,7 +7,7 @@ func isPowerOfThree(n int) bool { } // 解法二 打表法 -func isPowerOfThree_1(n int) bool { +func isPowerOfThree1(n int) bool { // 1162261467 is 3^19, 3^20 is bigger than int allPowerOfThreeMap := map[int]int{1: 1, 3: 3, 9: 9, 27: 27, 81: 81, 243: 243, 729: 729, 2187: 2187, 6561: 6561, 19683: 19683, 59049: 59049, 177147: 177147, 531441: 531441, 1594323: 1594323, 4782969: 4782969, 14348907: 14348907, 43046721: 43046721, 129140163: 129140163, 387420489: 387420489, 1162261467: 1162261467} _, ok := allPowerOfThreeMap[n] @@ -15,7 +15,7 @@ func isPowerOfThree_1(n int) bool { } // 解法三 循环 -func isPowerOfThree_2(num int) bool { +func isPowerOfThree2(num int) bool { for num >= 3 { if num%3 == 0 { num = num / 3 diff --git a/Algorithms/0342. Power of Four/342. Power of Four.go b/Algorithms/0342. Power of Four/342. Power of Four.go index 4f28b2b9..94b65da3 100644 --- a/Algorithms/0342. Power of Four/342. Power of Four.go +++ b/Algorithms/0342. Power of Four/342. Power of Four.go @@ -6,7 +6,7 @@ func isPowerOfFour(num int) bool { } // 解法二 循环 -func isPowerOfFour_(num int) bool { +func isPowerOfFour1(num int) bool { for num >= 4 { if num%4 == 0 { num = num / 4 diff --git a/Algorithms/0343. Integer Break/343. Integer Break.go b/Algorithms/0343. Integer Break/343. Integer Break.go index 7de9532b..0a30e343 100644 --- a/Algorithms/0343. Integer Break/343. Integer Break.go +++ b/Algorithms/0343. Integer Break/343. Integer Break.go @@ -1,7 +1,7 @@ package leetcode func integerBreak(n int) int { - var dp []int = make([]int, n+1) + dp := make([]int, n+1) dp[0], dp[1] = 1, 1 for i := 1; i <= n; i++ { for j := 1; j < i; j++ { diff --git a/Algorithms/0345. Reverse Vowels of a String/345. Reverse Vowels of a String.go b/Algorithms/0345. Reverse Vowels of a String/345. Reverse Vowels of a String.go index f462550d..3bd3fbee 100644 --- a/Algorithms/0345. Reverse Vowels of a String/345. Reverse Vowels of a String.go +++ b/Algorithms/0345. Reverse Vowels of a String/345. Reverse Vowels of a String.go @@ -22,7 +22,6 @@ func reverseVowels(s string) string { func isVowels(s byte) bool { if s == 'a' || s == 'e' || s == 'i' || s == 'o' || s == 'u' || s == 'A' || s == 'E' || s == 'I' || s == 'O' || s == 'U' { return true - } else { - return false } + return false } diff --git a/Algorithms/0347. Top K Frequent Elements/347. Top K Frequent Elements.go b/Algorithms/0347. Top K Frequent Elements/347. Top K Frequent Elements.go index 04d47fd4..a7362b19 100644 --- a/Algorithms/0347. Top K Frequent Elements/347. Top K Frequent Elements.go +++ b/Algorithms/0347. Top K Frequent Elements/347. Top K Frequent Elements.go @@ -19,6 +19,7 @@ func topKFrequent(nums []int, k int) []int { return result } +// Item define type Item struct { key int count int @@ -40,11 +41,13 @@ func (pq PriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } +// Push define func (pq *PriorityQueue) Push(x interface{}) { item := x.(*Item) *pq = append(*pq, item) } +// Pop define func (pq *PriorityQueue) Pop() interface{} { n := len(*pq) item := (*pq)[n-1] diff --git a/Algorithms/0357. Count Numbers with Unique Digits/357. Count Numbers with Unique Digits.go b/Algorithms/0357. Count Numbers with Unique Digits/357. Count Numbers with Unique Digits.go index 1b3436c9..aa58f957 100644 --- a/Algorithms/0357. Count Numbers with Unique Digits/357. Count Numbers with Unique Digits.go +++ b/Algorithms/0357. Count Numbers with Unique Digits/357. Count Numbers with Unique Digits.go @@ -1,7 +1,7 @@ package leetcode // 暴力打表法 -func countNumbersWithUniqueDigits_(n int) int { +func countNumbersWithUniqueDigits1(n int) int { res := []int{1, 10, 91, 739, 5275, 32491, 168571, 712891, 2345851, 5611771, 8877691} if n >= 10 { return res[10] diff --git a/Algorithms/0392. Is Subsequence/392. Is Subsequence.go b/Algorithms/0392. Is Subsequence/392. Is Subsequence.go index e69e561d..0c9027b9 100644 --- a/Algorithms/0392. Is Subsequence/392. Is Subsequence.go +++ b/Algorithms/0392. Is Subsequence/392. Is Subsequence.go @@ -22,7 +22,7 @@ func isSubsequence(s string, t string) bool { } // 解法二 O(n) -func isSubsequence_(s string, t string) bool { +func isSubsequence1(s string, t string) bool { for len(s) > 0 && len(t) > 0 { if s[0] == t[0] { s = s[1:] 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 b08abc07..e4e9cf4f 100644 --- a/Algorithms/0433. Minimum Genetic Mutation/433. Minimum Genetic Mutation.go +++ b/Algorithms/0433. Minimum Genetic Mutation/433. Minimum Genetic Mutation.go @@ -9,7 +9,7 @@ func minMutation(start string, end string, bank []string) int { for i := 0; i < qlen; i++ { word := que[0] que = que[1:] - candidates := getCandidates_(word) + candidates := getCandidates433(word) for _, candidate := range candidates { if _, ok := wordMap[candidate]; ok { if candidate == end { @@ -24,7 +24,7 @@ func minMutation(start string, end string, bank []string) int { return -1 } -func getCandidates_(word string) []string { +func getCandidates433(word string) []string { var res []string for i := 0; i < 26; i++ { for j := 0; j < len(word); j++ { @@ -37,7 +37,7 @@ func getCandidates_(word string) []string { } // 解法二 DFS -func minMutation_(start string, end string, bank []string) int { +func minMutation1(start string, end string, bank []string) int { endGene := convert(end) startGene := convert(start) m := make(map[uint32]struct{}) @@ -96,7 +96,7 @@ func check(val uint32) bool { } func convert(gene string) uint32 { - var v uint32 = 0 + var v uint32 for _, c := range gene { v <<= 2 switch c { 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 7e3b4a99..6a3fcc4d 100644 --- a/Algorithms/0435. Non-overlapping Intervals/435. Non-overlapping Intervals.go +++ b/Algorithms/0435. Non-overlapping Intervals/435. Non-overlapping Intervals.go @@ -11,7 +11,7 @@ func eraseOverlapIntervals(intervals [][]int) int { } sort.Sort(Intervals(intervals)) dp, res := make([]int, len(intervals)), 0 - for i, _ := range dp { + for i := range dp { dp[i] = 1 } for i := 1; i < len(intervals); i++ { @@ -27,6 +27,7 @@ func eraseOverlapIntervals(intervals [][]int) int { return len(intervals) - res } +// Intervals define type Intervals [][]int func (a Intervals) Len() int { @@ -49,7 +50,7 @@ func (a Intervals) Less(i, j int) bool { } // 解法二 贪心 O(n) -func eraseOverlapIntervals_(intervals [][]int) int { +func eraseOverlapIntervals1(intervals [][]int) int { if len(intervals) == 0 { return 0 } diff --git a/Algorithms/0435. Non-overlapping Intervals/435. Non-overlapping Intervals_test.go b/Algorithms/0435. Non-overlapping Intervals/435. Non-overlapping Intervals_test.go index 13bf7450..3050bc8a 100644 --- a/Algorithms/0435. Non-overlapping Intervals/435. Non-overlapping Intervals_test.go +++ b/Algorithms/0435. Non-overlapping Intervals/435. Non-overlapping Intervals_test.go @@ -46,7 +46,7 @@ func Test_Problem435(t *testing.T) { for _, q := range qs { _, p := q.ans435, q.para435 - fmt.Printf("【input】:%v 【output】:%v\n", p, eraseOverlapIntervals_(p.one)) + fmt.Printf("【input】:%v 【output】:%v\n", p, eraseOverlapIntervals1(p.one)) } fmt.Printf("\n\n\n") } 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 6e9f979a..29adc8e7 100644 --- a/Algorithms/0437. Path Sum III/437. Path Sum III.go +++ b/Algorithms/0437. Path Sum III/437. Path Sum III.go @@ -8,26 +8,26 @@ package leetcode * Right *TreeNode * } */ -func pathSum_III(root *TreeNode, sum int) int { +func pathSumIII(root *TreeNode, sum int) int { if root == nil { return 0 } - res := findPath_(root, sum) - res += pathSum_III(root.Left, sum) - res += pathSum_III(root.Right, sum) + res := findPath437(root, sum) + res += pathSumIII(root.Left, sum) + res += pathSumIII(root.Right, sum) return res } // 寻找包含 root 这个结点,且和为 sum 的路径 -func findPath_(root *TreeNode, sum int) int { +func findPath437(root *TreeNode, sum int) int { if root == nil { return 0 } res := 0 if root.Val == sum { - res += 1 + res++ } - res += findPath_(root.Left, sum-root.Val) - res += findPath_(root.Right, sum-root.Val) + res += findPath437(root.Left, sum-root.Val) + res += findPath437(root.Right, sum-root.Val) return res } 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 b4d600a3..71a727d7 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 @@ -43,7 +43,7 @@ func Test_Problem437(t *testing.T) { _, p := q.ans437, q.para437 fmt.Printf("【input】:%v ", p) root := Ints2TreeNode(p.one) - fmt.Printf("【output】:%v \n", pathSum_III(root, p.sum)) + 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 efbc5329..68822c1c 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 @@ -7,7 +7,7 @@ package leetcode * Next *ListNode * } */ -func addTwoNumbers_(l1 *ListNode, l2 *ListNode) *ListNode { +func addTwoNumbers445(l1 *ListNode, l2 *ListNode) *ListNode { if l1 == nil { return l2 } 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 c036c825..2c1bd352 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 @@ -73,7 +73,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(addTwoNumbers_(S2l(p.one), S2l(p.another)))) + fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(addTwoNumbers445(S2l(p.one), S2l(p.another)))) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0456. 132 Pattern/456. 132 Pattern.go b/Algorithms/0456. 132 Pattern/456. 132 Pattern.go index 35052818..89a75e6b 100644 --- a/Algorithms/0456. 132 Pattern/456. 132 Pattern.go +++ b/Algorithms/0456. 132 Pattern/456. 132 Pattern.go @@ -26,7 +26,7 @@ func find132pattern(nums []int) bool { } // 解法二 暴力解法,超时! -func find132pattern_(nums []int) bool { +func find132pattern1(nums []int) bool { if len(nums) < 3 { return false } diff --git a/Algorithms/0480. Sliding Window Median/480. Sliding Window Median.go b/Algorithms/0480. Sliding Window Median/480. Sliding Window Median.go index 7598c12c..40fcae4e 100644 --- a/Algorithms/0480. Sliding Window Median/480. Sliding Window Median.go +++ b/Algorithms/0480. Sliding Window Median/480. Sliding Window Median.go @@ -58,10 +58,9 @@ func getMedian(w *list.List, k int) float64 { } if k%2 == 1 { return float64(e.Value.(int)) - } else { - p := e.Prev() - return (float64(e.Value.(int)) + float64(p.Value.(int))) / 2 } + p := e.Prev() + return (float64(e.Value.(int)) + float64(p.Value.(int))) / 2 } // 解法二 用两个堆实现 时间复杂度 O(n * log k) 空间复杂度 O(k) @@ -70,7 +69,7 @@ func getMedian(w *list.List, k int) float64 { // 如果 k 是偶数,那么两个堆都有 k/2 个元素,中间值就是两个堆顶的元素 // 如果 k 是奇数,那么小顶堆比大顶堆多一个元素,中间值就是小顶堆的堆顶元素 // 删除一个元素,元素都标记到删除的堆中,取 top 的时候注意需要取出没有删除的元素 -func medianSlidingWindow_(nums []int, k int) []float64 { +func medianSlidingWindow1(nums []int, k int) []float64 { ans := []float64{} minH := MinHeapR{} maxH := MaxHeapR{} @@ -109,39 +108,57 @@ func medianSlidingWindow_(nums []int, k int) []float64 { return ans } +// IntHeap define type IntHeap struct { data []int } -func (h IntHeap) Len() int { return len(h.data) } -func (h IntHeap) Swap(i, j int) { h.data[i], h.data[j] = h.data[j], h.data[i] } +// Len define +func (h IntHeap) Len() int { return len(h.data) } + +// Swap define +func (h IntHeap) Swap(i, j int) { h.data[i], h.data[j] = h.data[j], h.data[i] } + +// Push define func (h *IntHeap) Push(x interface{}) { h.data = append(h.data, x.(int)) } + +// Pop define func (h *IntHeap) Pop() interface{} { x := h.data[h.Len()-1] h.data = h.data[0 : h.Len()-1] return x } + +// Top defines func (h IntHeap) Top() int { return h.data[0] } +// MinHeap define type MinHeap struct { IntHeap } +// Less define func (h MinHeap) Less(i, j int) bool { return h.data[i] < h.data[j] } +// MaxHeap define type MaxHeap struct { IntHeap } +// Less define func (h MaxHeap) Less(i, j int) bool { return h.data[i] > h.data[j] } +// MinHeapR define type MinHeapR struct { hp, hpDel MinHeap } +// Len define func (h MinHeapR) Len() int { return h.hp.Len() - h.hpDel.Len() } + +// Top define func (h *MinHeapR) Top() int { for h.hpDel.Len() > 0 && h.hp.Top() == h.hpDel.Top() { heap.Pop(&h.hp) @@ -149,19 +166,29 @@ func (h *MinHeapR) Top() int { } return h.hp.Top() } + +// Pop define func (h *MinHeapR) Pop() int { x := h.Top() heap.Pop(&h.hp) return x } -func (h *MinHeapR) Push(x int) { heap.Push(&h.hp, x) } + +// Push define +func (h *MinHeapR) Push(x int) { heap.Push(&h.hp, x) } + +// Remove define func (h *MinHeapR) Remove(x int) { heap.Push(&h.hpDel, x) } +// MaxHeapR define type MaxHeapR struct { hp, hpDel MaxHeap } +// Len define func (h MaxHeapR) Len() int { return h.hp.Len() - h.hpDel.Len() } + +// Top define func (h *MaxHeapR) Top() int { for h.hpDel.Len() > 0 && h.hp.Top() == h.hpDel.Top() { heap.Pop(&h.hp) @@ -169,10 +196,16 @@ func (h *MaxHeapR) Top() int { } return h.hp.Top() } + +// Pop define func (h *MaxHeapR) Pop() int { x := h.Top() heap.Pop(&h.hp) return x } -func (h *MaxHeapR) Push(x int) { heap.Push(&h.hp, x) } + +// Push define +func (h *MaxHeapR) Push(x int) { heap.Push(&h.hp, x) } + +// Remove define func (h *MaxHeapR) Remove(x int) { heap.Push(&h.hpDel, x) } diff --git a/Algorithms/0480. Sliding Window Median/480. Sliding Window Median_test.go b/Algorithms/0480. Sliding Window Median/480. Sliding Window Median_test.go index 54b5dd86..d5f3cfd6 100644 --- a/Algorithms/0480. Sliding Window Median/480. Sliding Window Median_test.go +++ b/Algorithms/0480. Sliding Window Median/480. Sliding Window Median_test.go @@ -37,7 +37,7 @@ func Test_Problem480(t *testing.T) { for _, q := range qs { _, p := q.ans480, q.para480 - fmt.Printf("【input】:%v 【output】:%v\n", p, medianSlidingWindow_(p.one, p.k)) + fmt.Printf("【input】:%v 【output】:%v\n", p, medianSlidingWindow1(p.one, p.k)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0503. Next Greater Element II/503. Next Greater Element II.go b/Algorithms/0503. Next Greater Element II/503. Next Greater Element II.go index de0006e9..16f1209f 100644 --- a/Algorithms/0503. Next Greater Element II/503. Next Greater Element II.go +++ b/Algorithms/0503. Next Greater Element II/503. Next Greater Element II.go @@ -20,7 +20,7 @@ func nextGreaterElements(nums []int) []int { } // 解法二 -func nextGreaterElements_(nums []int) []int { +func nextGreaterElements1(nums []int) []int { if len(nums) == 0 { return []int{} } 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 def99516..812adbe8 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 @@ -26,7 +26,7 @@ func largestValues(root *TreeNode) []int { } // 解法二 层序遍历二叉树,遍历过程中不断更新最大值 -func largestValues_(root *TreeNode) []int { +func largestValues1(root *TreeNode) []int { if root == nil { return []int{} } diff --git a/Algorithms/0524. Longest Word in Dictionary through Deleting/524. Longest Word in Dictionary through Deleting.go b/Algorithms/0524. Longest Word in Dictionary through Deleting/524. Longest Word in Dictionary through Deleting.go index 660d2f53..decf07b2 100644 --- a/Algorithms/0524. Longest Word in Dictionary through Deleting/524. Longest Word in Dictionary through Deleting.go +++ b/Algorithms/0524. Longest Word in Dictionary through Deleting/524. Longest Word in Dictionary through Deleting.go @@ -7,7 +7,7 @@ func findLongestWord(s string, d []string) string { pointD := 0 for pointS < len(s) && pointD < len(d[i]) { if s[pointS] == d[i][pointD] { - pointD += 1 + pointD++ } pointS++ } diff --git a/Algorithms/0526. Beautiful Arrangement/526. Beautiful Arrangement.go b/Algorithms/0526. Beautiful Arrangement/526. Beautiful Arrangement.go index b7289e8b..2f0015c8 100644 --- a/Algorithms/0526. Beautiful Arrangement/526. Beautiful Arrangement.go +++ b/Algorithms/0526. Beautiful Arrangement/526. Beautiful Arrangement.go @@ -1,7 +1,7 @@ package leetcode // 解法一 暴力打表法 -func countArrangement_(N int) int { +func countArrangement1(N int) int { res := []int{0, 1, 2, 3, 8, 10, 36, 41, 132, 250, 700, 750, 4010, 4237, 10680, 24679, 87328, 90478, 435812} return res[N] } @@ -12,14 +12,14 @@ func countArrangement(N int) int { return 0 } nums, used, p, res := make([]int, N), make([]bool, N), []int{}, [][]int{} - for i, _ := range nums { + for i := range nums { nums[i] = i + 1 } - generatePermutation_526(nums, 0, p, &res, &used) + generatePermutation526(nums, 0, p, &res, &used) return len(res) } -func generatePermutation_526(nums []int, index int, p []int, res *[][]int, used *[]bool) { +func generatePermutation526(nums []int, index int, p []int, res *[][]int, used *[]bool) { if index == len(nums) { temp := make([]int, len(p)) copy(temp, p) @@ -33,7 +33,7 @@ func generatePermutation_526(nums []int, index int, p []int, res *[][]int, used } (*used)[i] = true p = append(p, nums[i]) - generatePermutation_526(nums, index+1, p, res, used) + generatePermutation526(nums, index+1, p, res, used) p = p[:len(p)-1] (*used)[i] = false } diff --git a/Algorithms/0532. K-diff Pairs in an Array/532. K-diff Pairs in an Array.go b/Algorithms/0532. K-diff Pairs in an Array/532. K-diff Pairs in an Array.go index 2f7bd54a..3fd7d1a6 100644 --- a/Algorithms/0532. K-diff Pairs in an Array/532. K-diff Pairs in an Array.go +++ b/Algorithms/0532. K-diff Pairs in an Array/532. K-diff Pairs in an Array.go @@ -9,7 +9,7 @@ func findPairs(nums []int, k int) int { for _, value := range nums { m[value]++ } - for key, _ := range m { + for key := range m { if k == 0 && m[key] > 1 { count++ continue diff --git a/Algorithms/0542. 01 Matrix/542. 01 Matrix.go b/Algorithms/0542. 01 Matrix/542. 01 Matrix.go index 46fa2ae1..6ee0cf10 100644 --- a/Algorithms/0542. 01 Matrix/542. 01 Matrix.go +++ b/Algorithms/0542. 01 Matrix/542. 01 Matrix.go @@ -5,15 +5,15 @@ import ( ) // 解法一 BFS -func updateMatrix_BFS(matrix [][]int) [][]int { +func updateMatrixBFS(matrix [][]int) [][]int { res := make([][]int, len(matrix)) if len(matrix) == 0 || len(matrix[0]) == 0 { return res } queue := make([][]int, 0) - for i, _ := range matrix { + for i := range matrix { res[i] = make([]int, len(matrix[0])) - for j, _ := range res[i] { + for j := range res[i] { if matrix[i][j] == 0 { res[i][j] = -1 queue = append(queue, []int{i, j}) @@ -24,7 +24,7 @@ func updateMatrix_BFS(matrix [][]int) [][]int { for len(queue) > 0 { size := len(queue) for size > 0 { - size -= 1 + size-- node := queue[0] queue = queue[1:] i, j := node[0], node[1] @@ -51,22 +51,22 @@ func updateMatrix_BFS(matrix [][]int) [][]int { } // 解法二 DFS -func updateMatrix_DFS(matrix [][]int) [][]int { +func updateMatrixDFS(matrix [][]int) [][]int { result := [][]int{} if len(matrix) == 0 || len(matrix[0]) == 0 { return result } - max_row, max_col := len(matrix), len(matrix[0]) - for r := 0; r < max_row; r++ { - for c := 0; c < max_col; c++ { + maxRow, maxCol := len(matrix), len(matrix[0]) + for r := 0; r < maxRow; r++ { + for c := 0; c < maxCol; c++ { if matrix[r][c] == 1 && hasZero(matrix, r, c) == false { // 将四周没有 0 的 1 特殊处理为最大值 matrix[r][c] = math.MaxInt64 } } } - for r := 0; r < max_row; r++ { - for c := 0; c < max_col; c++ { + for r := 0; r < maxRow; r++ { + for c := 0; c < maxCol; c++ { if matrix[r][c] == 1 { dfsMatrix(matrix, r, c, -1) } @@ -107,7 +107,7 @@ func dfsMatrix(matrix [][]int, row, col, val int) { } // 解法三 DP -func updateMatrix_DP(matrix [][]int) [][]int { +func updateMatrixDP(matrix [][]int) [][]int { for i, row := range matrix { for j, val := range row { if val == 0 { diff --git a/Algorithms/0542. 01 Matrix/542. 01 Matrix_test.go b/Algorithms/0542. 01 Matrix/542. 01 Matrix_test.go index 3de292bc..efebe43b 100644 --- a/Algorithms/0542. 01 Matrix/542. 01 Matrix_test.go +++ b/Algorithms/0542. 01 Matrix/542. 01 Matrix_test.go @@ -46,7 +46,7 @@ func Test_Problem542(t *testing.T) { for _, q := range qs { _, p := q.ans542, q.para542 - fmt.Printf("【input】:%v 【output】:%v\n", p, updateMatrix_DP(p.one)) + fmt.Printf("【input】:%v 【output】:%v\n", p, updateMatrixDP(p.one)) } 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 b08f9d38..41b7a78a 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 @@ -24,7 +24,7 @@ func maximumProduct(nums []int) int { } // 解法二 模拟,时间复杂度 O(n) -func maximumProduct_(nums []int) int { +func maximumProduct1(nums []int) int { n1, n2, n3 := -1<<63, -1<<63, -1<<63 n4, n5 := 0, 0 for _, v := range nums { @@ -47,7 +47,6 @@ func maximumProduct_(nums []int) int { } if n2*n3 > n4*n5 { return n1 * n2 * n3 - } else { - return n1 * n4 * n5 } + return n1 * n4 * n5 } diff --git a/Algorithms/0648. Replace Words/648. Replace Words.go b/Algorithms/0648. Replace Words/648. Replace Words.go index fd2bdb77..03745208 100644 --- a/Algorithms/0648. Replace Words/648. Replace Words.go +++ b/Algorithms/0648. Replace Words/648. Replace Words.go @@ -35,8 +35,8 @@ func findWord(roots map[byte][]string, word []byte) bool { } //解法二 Trie -func replaceWords_(dict []string, sentence string) string { - trie := Constructor_208() +func replaceWords1(dict []string, sentence string) string { + trie := Constructor208() for _, v := range dict { trie.Insert(v) } diff --git a/Algorithms/0676. Implement Magic Dictionary/676. Implement Magic Dictionary.go b/Algorithms/0676. Implement Magic Dictionary/676. Implement Magic Dictionary.go index 37daaa70..24f81e6b 100644 --- a/Algorithms/0676. Implement Magic Dictionary/676. Implement Magic Dictionary.go +++ b/Algorithms/0676. Implement Magic Dictionary/676. Implement Magic Dictionary.go @@ -5,7 +5,7 @@ type MagicDictionary struct { } /** Initialize your data structure here. */ -func Constructor_676() MagicDictionary { +func Constructor676() MagicDictionary { return MagicDictionary{rdict: make(map[int]string)} } diff --git a/Algorithms/0676. Implement Magic Dictionary/676. Implement Magic Dictionary_test.go b/Algorithms/0676. Implement Magic Dictionary/676. Implement Magic Dictionary_test.go index 51b857f7..a88e424d 100644 --- a/Algorithms/0676. Implement Magic Dictionary/676. Implement Magic Dictionary_test.go +++ b/Algorithms/0676. Implement Magic Dictionary/676. Implement Magic Dictionary_test.go @@ -7,7 +7,7 @@ import ( func Test_Problem676(t *testing.T) { dict := []string{"hello", "leetcode"} - obj := Constructor_676() + obj := Constructor676() obj.BuildDict(dict) fmt.Printf("obj = %v\n", obj) fmt.Println(obj.Search("hello")) diff --git a/Algorithms/0682. Baseball Game/682. Baseball Game.go b/Algorithms/0682. Baseball Game/682. Baseball Game.go index 86b706b6..2a5a9851 100644 --- a/Algorithms/0682. Baseball Game/682. Baseball Game.go +++ b/Algorithms/0682. Baseball Game/682. Baseball Game.go @@ -13,16 +13,16 @@ func calPoints(ops []string) int { last1 := stack[top-1] last2 := stack[top-2] stack[top] = last1 + last2 - top += 1 + top++ case "D": last1 := stack[top-1] stack[top] = last1 * 2 - top += 1 + top++ case "C": - top -= 1 + top-- default: stack[top], _ = strconv.Atoi(op) - top += 1 + top++ } } 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 3fc11cca..790da6ea 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 @@ -8,8 +8,8 @@ import ( func Test_Problem707(t *testing.T) { obj := Constructor() fmt.Printf("obj = %v\n", ML2s(&obj)) - param_1 := obj.Get(1) - fmt.Printf("param_1 = %v obj = %v\n", param_1, ML2s(&obj)) + param1 := obj.Get(1) + fmt.Printf("param_1 = %v obj = %v\n", param1, ML2s(&obj)) obj.AddAtHead(38) fmt.Printf("obj = %v\n", ML2s(&obj)) obj.AddAtHead(45) @@ -36,20 +36,20 @@ func Test_Problem707(t *testing.T) { obj1 := Constructor() fmt.Printf("obj1 = %v\n", ML2s(&obj1)) - param_2 := obj1.Get(0) - fmt.Printf("param_2 = %v obj1 = %v\n", param_2, ML2s(&obj1)) + param2 := obj1.Get(0) + fmt.Printf("param_2 = %v obj1 = %v\n", param2, ML2s(&obj1)) obj1.AddAtIndex(1, 2) fmt.Printf("obj1 = %v\n", ML2s(&obj1)) - param_2 = obj1.Get(0) - fmt.Printf("param_2 = %v obj1 = %v\n", param_2, ML2s(&obj1)) - param_2 = obj1.Get(1) - fmt.Printf("param_2 = %v obj1 = %v\n", param_2, ML2s(&obj1)) + param2 = obj1.Get(0) + fmt.Printf("param_2 = %v obj1 = %v\n", param2, ML2s(&obj1)) + param2 = obj1.Get(1) + fmt.Printf("param_2 = %v obj1 = %v\n", param2, ML2s(&obj1)) obj1.AddAtIndex(0, 1) fmt.Printf("obj1 = %v\n", ML2s(&obj1)) - param_2 = obj1.Get(0) - fmt.Printf("param_1 = %v obj1 = %v\n", param_2, ML2s(&obj1)) - param_2 = obj1.Get(1) - fmt.Printf("param_2 = %v obj1 = %v\n", param_2, ML2s(&obj1)) + param2 = obj1.Get(0) + fmt.Printf("param_1 = %v obj1 = %v\n", param2, ML2s(&obj1)) + param2 = obj1.Get(1) + fmt.Printf("param_2 = %v obj1 = %v\n", param2, ML2s(&obj1)) } func ML2s(head *MyLinkedList) []int { diff --git a/Algorithms/0710. Random Pick with Blacklist/710. Random Pick with Blacklist.go b/Algorithms/0710. Random Pick with Blacklist/710. Random Pick with Blacklist.go index eab2885f..3a93a7c6 100644 --- a/Algorithms/0710. Random Pick with Blacklist/710. Random Pick with Blacklist.go +++ b/Algorithms/0710. Random Pick with Blacklist/710. Random Pick with Blacklist.go @@ -7,7 +7,7 @@ type Solution struct { BlackMap map[int]int } -func Constructor_710(N int, blacklist []int) Solution { +func Constructor710(N int, blacklist []int) Solution { blackMap := map[int]int{} for i := 0; i < len(blacklist); i++ { blackMap[blacklist[i]] = 1 diff --git a/Algorithms/0710. Random Pick with Blacklist/710. Random Pick with Blacklist_test.go b/Algorithms/0710. Random Pick with Blacklist/710. Random Pick with Blacklist_test.go index e16cbab1..a1732ae4 100644 --- a/Algorithms/0710. Random Pick with Blacklist/710. Random Pick with Blacklist_test.go +++ b/Algorithms/0710. Random Pick with Blacklist/710. Random Pick with Blacklist_test.go @@ -59,7 +59,7 @@ func Test_Problem710(t *testing.T) { for _, q := range qs { _, p := q.ans710, q.para710 fmt.Printf("【input】: n = %v blacklist = %v pick times = %v ", p.n, p.blackList, p.times) - obj := Constructor_710(p.n, p.blackList) + obj := Constructor710(p.n, p.blackList) fmt.Printf("【output】:") for i := 0; i < p.times; i++ { fmt.Printf(" %v ,", obj.Pick()) 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 2d15ce9f..2a284759 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 @@ -5,12 +5,12 @@ import ( ) // 解法一 模拟 DP -func maxProfit_714(prices []int, fee int) int { +func maxProfit714(prices []int, fee int) int { if len(prices) <= 1 { return 0 } buy, sell := make([]int, len(prices)), make([]int, len(prices)) - for i, _ := range buy { + for i := range buy { buy[i] = math.MinInt64 } buy[0] = -prices[0] @@ -22,7 +22,7 @@ func maxProfit_714(prices []int, fee int) int { } // 解法二 优化辅助空间的 DP -func maxProfit_714_(prices []int, fee int) int { +func maxProfit714_1(prices []int, fee int) int { sell, buy := 0, -prices[0] for i := 1; i < len(prices); i++ { sell = max(sell, buy+prices[i]-fee) 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 1673be04..d4eb73e5 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 @@ -52,7 +52,7 @@ func Test_Problem714(t *testing.T) { for _, q := range qs { _, p := q.ans714, q.para714 - fmt.Printf("【input】:%v 【output】:%v\n", p, maxProfit_714(p.one, p.f)) + fmt.Printf("【input】:%v 【output】:%v\n", p, maxProfit714(p.one, p.f)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/0726. Number of Atoms/726. Number of Atoms.go b/Algorithms/0726. Number of Atoms/726. Number of Atoms.go index 10dfdd6c..c05e2594 100644 --- a/Algorithms/0726. Number of Atoms/726. Number of Atoms.go +++ b/Algorithms/0726. Number of Atoms/726. Number of Atoms.go @@ -98,23 +98,20 @@ func countOfAtoms(s string) string { func isDigital(v byte) bool { if v >= '0' && v <= '9' { return true - } else { - return false } + return false } func isUpperLetter(v byte) bool { if v >= 'A' && v <= 'Z' { return true - } else { - return false } + return false } func isLowerLetter(v byte) bool { if v >= 'a' && v <= 'z' { return true - } else { - return false } + return false } diff --git a/Algorithms/0739. Daily Temperatures/739. Daily Temperatures.go b/Algorithms/0739. Daily Temperatures/739. Daily Temperatures.go index cf408707..5a6f8ecc 100644 --- a/Algorithms/0739. Daily Temperatures/739. Daily Temperatures.go +++ b/Algorithms/0739. Daily Temperatures/739. Daily Temperatures.go @@ -15,7 +15,7 @@ func dailyTemperatures(T []int) []int { } // 解法二 单调栈 -func dailyTemperatures_(T []int) []int { +func dailyTemperatures1(T []int) []int { res := make([]int, len(T)) var toCheck []int for i, t := range T { diff --git a/Algorithms/0745. Prefix and Suffix Search/745. Prefix and Suffix Search.go b/Algorithms/0745. Prefix and Suffix Search/745. Prefix and Suffix Search.go index c122c8c8..da7c86be 100644 --- a/Algorithms/0745. Prefix and Suffix Search/745. Prefix and Suffix Search.go +++ b/Algorithms/0745. Prefix and Suffix Search/745. Prefix and Suffix Search.go @@ -7,7 +7,7 @@ type WordFilter struct { words map[string]int } -func Constructor_745(words []string) WordFilter { +func Constructor745(words []string) WordFilter { wordsMap := make(map[string]int, len(words)*5) for k := 0; k < len(words); k++ { for i := 0; i <= 10 && i <= len(words[k]); i++ { diff --git a/Algorithms/0745. Prefix and Suffix Search/745. Prefix and Suffix Search_test.go b/Algorithms/0745. Prefix and Suffix Search/745. Prefix and Suffix Search_test.go index a7815445..02e147e9 100644 --- a/Algorithms/0745. Prefix and Suffix Search/745. Prefix and Suffix Search_test.go +++ b/Algorithms/0745. Prefix and Suffix Search/745. Prefix and Suffix Search_test.go @@ -6,10 +6,10 @@ import ( ) func Test_Problem745(t *testing.T) { - obj := Constructor_745([]string{"apple"}) + obj := Constructor745([]string{"apple"}) fmt.Printf("obj = %v\n", obj) - param_1 := obj.F("a", "e") - fmt.Printf("param_1 = %v obj = %v\n", param_1, obj) - param_2 := obj.F("b", "") - fmt.Printf("param_2 = %v obj = %v\n", param_2, obj) + param1 := obj.F("a", "e") + fmt.Printf("param_1 = %v obj = %v\n", param1, obj) + param2 := obj.F("b", "") + fmt.Printf("param_2 = %v obj = %v\n", param2, obj) } 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 4914b3eb..ac475d2f 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 @@ -11,7 +11,7 @@ func minCostClimbingStairs(cost []int) int { } // 解法二 DP 优化辅助空间 -func minCostClimbingStairs_(cost []int) int { +func minCostClimbingStairs1(cost []int) int { var cur, last int for i := 2; i < len(cost)+1; i++ { if last+cost[i-1] > cur+cost[i-2] { diff --git a/Algorithms/0763. Partition Labels/763. Partition Labels.go b/Algorithms/0763. Partition Labels/763. Partition Labels.go index 114def83..70cc2f74 100644 --- a/Algorithms/0763. Partition Labels/763. Partition Labels.go +++ b/Algorithms/0763. Partition Labels/763. Partition Labels.go @@ -21,7 +21,7 @@ func partitionLabels(S string) []int { } // 解法二 -func partitionLabels_(S string) []int { +func partitionLabels1(S string) []int { visit, counter, res, sum, lastLength := make([]int, 26), map[byte]int{}, []int{}, 0, 0 for i := 0; i < len(S); i++ { counter[S[i]]++ diff --git a/Algorithms/0767. Reorganize String/767. Reorganize String.go b/Algorithms/0767. Reorganize String/767. Reorganize String.go index a15d57d9..485c43a6 100644 --- a/Algorithms/0767. Reorganize String/767. Reorganize String.go +++ b/Algorithms/0767. Reorganize String/767. Reorganize String.go @@ -5,7 +5,7 @@ import ( ) func reorganizeString(S string) string { - fs := frequencySort_(S) + fs := frequencySort767(S) if fs == "" { return "" } @@ -22,7 +22,7 @@ func reorganizeString(S string) string { return ans } -func frequencySort_(s string) string { +func frequencySort767(s string) string { if s == "" { return "" } 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 adbb5b32..5708cbb9 100644 --- a/Algorithms/0784. Letter Case Permutation/784. Letter Case Permutation.go +++ b/Algorithms/0784. Letter Case Permutation/784. Letter Case Permutation.go @@ -46,11 +46,11 @@ func findLetterCasePermutation(s string, pos []int, target, index int, c []int, // 第二步: // [mqe Mqe mQe MQe] -> [mqe Mqe mQe MQe mqE MqE mQE MQE] -func letterCasePermutation_(S string) []string { +func letterCasePermutation1(S string) []string { res := make([]string, 0, 1<= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') } diff --git a/Algorithms/0784. Letter Case Permutation/784. Letter Case Permutation_test.go b/Algorithms/0784. Letter Case Permutation/784. Letter Case Permutation_test.go index b93f343c..5eb38516 100644 --- a/Algorithms/0784. Letter Case Permutation/784. Letter Case Permutation_test.go +++ b/Algorithms/0784. Letter Case Permutation/784. Letter Case Permutation_test.go @@ -56,7 +56,7 @@ func Test_Problem784(t *testing.T) { for _, q := range qs { _, p := q.ans784, q.para784 - fmt.Printf("【input】:%v 【output】:%v\n", p, letterCasePermutation_(p.one)) + fmt.Printf("【input】:%v 【output】:%v\n", p, letterCasePermutation1(p.one)) } 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 6ac2d4b4..9c353278 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 @@ -5,18 +5,25 @@ import ( "sort" ) +// Task define type Task struct { Difficulty int Profit int } +// Tasks define type Tasks []Task -func (p Tasks) Len() int { return len(p) } +// Len define +func (p Tasks) Len() int { return len(p) } + +// Swap define func (p Tasks) Swap(i, j int) { p[i], p[j] = p[j], p[i] } +// SortByDiff define type SortByDiff struct{ Tasks } +// Less define func (p SortByDiff) Less(i, j int) bool { return p.Tasks[i].Difficulty < p.Tasks[j].Difficulty } diff --git a/Algorithms/0828. Unique Letter String/828. Unique Letter String.go b/Algorithms/0828. Unique Letter String/828. Unique Letter String.go index 0d4c64d7..92dd5f76 100644 --- a/Algorithms/0828. Unique Letter String/828. Unique Letter String.go +++ b/Algorithms/0828. Unique Letter String/828. Unique Letter String.go @@ -17,7 +17,7 @@ func uniqueLetterString(S string) int { } // 暴力解法,超时!时间复杂度 O(n^2) -func uniqueLetterString_(S string) int { +func uniqueLetterString1(S string) int { if len(S) == 0 { return 0 } diff --git a/Algorithms/0838. Push Dominoes/838. Push Dominoes.go b/Algorithms/0838. Push Dominoes/838. Push Dominoes.go index b40d52ee..49e004f0 100644 --- a/Algorithms/0838. Push Dominoes/838. Push Dominoes.go +++ b/Algorithms/0838. Push Dominoes/838. Push Dominoes.go @@ -40,7 +40,7 @@ func push(d []byte) { } // 解法二 -func pushDominoes_(dominoes string) string { +func pushDominoes1(dominoes string) string { dominoes = "L" + dominoes + "R" res := "" for i, j := 0, 1; j < len(dominoes); j++ { 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 9f13aa57..2469ded4 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 @@ -49,10 +49,9 @@ func findRecursiveCheck(S string, x1 int, x2 int, left int, res *[]int, isComple *res = append(*res, x1) findRecursiveCheck(S, x2, x1+x2, left+len(strconv.Itoa(x1+x2)), res, isComplete) return - } else { - if len(*res) > 0 && !*isComplete { - *res = (*res)[:len(*res)-1] - } + } + if len(*res) > 0 && !*isComplete { + *res = (*res)[:len(*res)-1] } return } diff --git a/Algorithms/0853. Car Fleet/853. Car Fleet.go b/Algorithms/0853. Car Fleet/853. Car Fleet.go index f927fd99..2989d20b 100644 --- a/Algorithms/0853. Car Fleet/853. Car Fleet.go +++ b/Algorithms/0853. Car Fleet/853. Car Fleet.go @@ -9,6 +9,7 @@ type car struct { position int } +// ByPosition define type ByPosition []car func (a ByPosition) Len() int { return len(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 ee885a40..3f13a1f0 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 @@ -26,7 +26,6 @@ func middleNode(head *ListNode) *ListNode { } if length%2 == 0 { return p1.Next - } else { - return p1 } + return p1 } diff --git a/Algorithms/0880. Decoded String at Index/880. Decoded String at Index.go b/Algorithms/0880. Decoded String at Index/880. Decoded String at Index.go index 1e40e2d4..c1ca8eac 100644 --- a/Algorithms/0880. Decoded String at Index/880. Decoded String at Index.go +++ b/Algorithms/0880. Decoded String at Index/880. Decoded String at Index.go @@ -3,9 +3,8 @@ package leetcode func isLetter(char byte) bool { if char >= 'a' && char <= 'z' { return true - } else { - return false } + return false } func decodeAtIndex(S string, K int) string { @@ -20,9 +19,8 @@ func decodeAtIndex(S string, K int) string { if length*int(S[i]-'0') >= K { if K%length != 0 { return decodeAtIndex(S[:i], K%length) - } else { - return decodeAtIndex(S[:i], length) } + return decodeAtIndex(S[:i], length) } length *= int(S[i] - '0') } diff --git a/Algorithms/0895. Maximum Frequency Stack/895. Maximum Frequency Stack.go b/Algorithms/0895. Maximum Frequency Stack/895. Maximum Frequency Stack.go index 61dcf754..2e519dc9 100644 --- a/Algorithms/0895. Maximum Frequency Stack/895. Maximum Frequency Stack.go +++ b/Algorithms/0895. Maximum Frequency Stack/895. Maximum Frequency Stack.go @@ -6,7 +6,7 @@ type FreqStack struct { maxfreq int } -func Constructor_895() FreqStack { +func Constructor895() FreqStack { hash := make(map[int]int) maxHash := make(map[int][]int) return FreqStack{freq: hash, group: maxHash} diff --git a/Algorithms/0895. Maximum Frequency Stack/895. Maximum Frequency Stack_test.go b/Algorithms/0895. Maximum Frequency Stack/895. Maximum Frequency Stack_test.go index 25ab7db9..6dbc01ea 100644 --- a/Algorithms/0895. Maximum Frequency Stack/895. Maximum Frequency Stack_test.go +++ b/Algorithms/0895. Maximum Frequency Stack/895. Maximum Frequency Stack_test.go @@ -6,7 +6,7 @@ import ( ) func Test_Problem895(t *testing.T) { - obj := Constructor_895() + obj := Constructor895() fmt.Printf("obj = %v\n", obj) obj.Push(5) fmt.Printf("obj = %v\n", obj) @@ -20,16 +20,16 @@ func Test_Problem895(t *testing.T) { fmt.Printf("obj = %v\n", obj) obj.Push(5) fmt.Printf("obj = %v\n", obj) - param_1 := obj.Pop() - fmt.Printf("param_1 = %v\n", param_1) - param_1 = obj.Pop() - fmt.Printf("param_1 = %v\n", param_1) - param_1 = obj.Pop() - fmt.Printf("param_1 = %v\n", param_1) - param_1 = obj.Pop() - fmt.Printf("param_1 = %v\n", param_1) - param_1 = obj.Pop() - fmt.Printf("param_1 = %v\n", param_1) - param_1 = obj.Pop() - fmt.Printf("param_1 = %v\n", param_1) + param1 := obj.Pop() + fmt.Printf("param_1 = %v\n", param1) + param1 = obj.Pop() + fmt.Printf("param_1 = %v\n", param1) + param1 = obj.Pop() + fmt.Printf("param_1 = %v\n", param1) + param1 = obj.Pop() + fmt.Printf("param_1 = %v\n", param1) + param1 = obj.Pop() + fmt.Printf("param_1 = %v\n", param1) + param1 = obj.Pop() + fmt.Printf("param_1 = %v\n", param1) } diff --git a/Algorithms/0901. Online Stock Span/901. Online Stock Span.go b/Algorithms/0901. Online Stock Span/901. Online Stock Span.go index 3ea0783d..c962aaf5 100644 --- a/Algorithms/0901. Online Stock Span/901. Online Stock Span.go +++ b/Algorithms/0901. Online Stock Span/901. Online Stock Span.go @@ -13,7 +13,7 @@ type StockSpanner struct { Item []Node } -func Constructor_901() StockSpanner { +func Constructor901() StockSpanner { stockSpanner := StockSpanner{make([]Node, 0)} return stockSpanner } diff --git a/Algorithms/0901. Online Stock Span/901. Online Stock Span_test.go b/Algorithms/0901. Online Stock Span/901. Online Stock Span_test.go index 058fc2e5..a70e4475 100644 --- a/Algorithms/0901. Online Stock Span/901. Online Stock Span_test.go +++ b/Algorithms/0901. Online Stock Span/901. Online Stock Span_test.go @@ -6,20 +6,20 @@ import ( ) func Test_Problem901(t *testing.T) { - obj := Constructor_901() + obj := Constructor901() fmt.Printf("obj = %v\n", obj) - param_1 := obj.Next(100) - fmt.Printf("param_1 = %v\n", param_1) - param_2 := obj.Next(80) - fmt.Printf("param_2 = %v\n", param_2) - param_3 := obj.Next(60) - fmt.Printf("param_3 = %v\n", param_3) - param_4 := obj.Next(70) - fmt.Printf("param_4 = %v\n", param_4) - param_5 := obj.Next(60) - fmt.Printf("param_5 = %v\n", param_5) - param_6 := obj.Next(75) - fmt.Printf("param_6 = %v\n", param_6) - param_7 := obj.Next(85) - fmt.Printf("param_7 = %v\n", param_7) + param1 := obj.Next(100) + fmt.Printf("param_1 = %v\n", param1) + param2 := obj.Next(80) + fmt.Printf("param_2 = %v\n", param2) + param3 := obj.Next(60) + fmt.Printf("param_3 = %v\n", param3) + param4 := obj.Next(70) + fmt.Printf("param_4 = %v\n", param4) + param5 := obj.Next(60) + fmt.Printf("param_5 = %v\n", param5) + param6 := obj.Next(75) + fmt.Printf("param_6 = %v\n", param6) + param7 := obj.Next(85) + fmt.Printf("param_7 = %v\n", param7) } diff --git a/Algorithms/0907. Sum of Subarray Minimums/907. Sum of Subarray Minimums.go b/Algorithms/0907. Sum of Subarray Minimums/907. Sum of Subarray Minimums.go index 6f7920e3..4cc2c989 100644 --- a/Algorithms/0907. Sum of Subarray Minimums/907. Sum of Subarray Minimums.go +++ b/Algorithms/0907. Sum of Subarray Minimums/907. Sum of Subarray Minimums.go @@ -23,7 +23,7 @@ type pair struct { } // 解法二 用两个单调栈 -func sumSubarrayMins_(A []int) int { +func sumSubarrayMins1(A []int) int { res, n, mod := 0, len(A), 1000000007 lefts, rights, leftStack, rightStack := make([]int, n), make([]int, n), []*pair{}, []*pair{} for i := 0; i < n; i++ { @@ -53,7 +53,7 @@ func sumSubarrayMins_(A []int) int { } // 解法三 暴力解法,中间很多重复判断子数组的情况 -func sumSubarrayMins__(A []int) int { +func sumSubarrayMins2(A []int) int { res, mod := 0, 1000000007 for i := 0; i < len(A); i++ { stack := []int{} diff --git a/Algorithms/0923. 3Sum With Multiplicity/923. 3Sum With Multiplicity.go b/Algorithms/0923. 3Sum With Multiplicity/923. 3Sum With Multiplicity.go index 0bad2e90..cd15c46a 100644 --- a/Algorithms/0923. 3Sum With Multiplicity/923. 3Sum With Multiplicity.go +++ b/Algorithms/0923. 3Sum With Multiplicity/923. 3Sum With Multiplicity.go @@ -12,7 +12,7 @@ func threeSumMulti(A []int, target int) int { } uniqNums := []int{} - for key, _ := range counter { + for key := range counter { uniqNums = append(uniqNums, key) } sort.Ints(uniqNums) diff --git a/Algorithms/0969. Pancake Sorting/969. Pancake Sorting.go b/Algorithms/0969. Pancake Sorting/969. Pancake Sorting.go index 6fe9b503..c67ce906 100644 --- a/Algorithms/0969. Pancake Sorting/969. Pancake Sorting.go +++ b/Algorithms/0969. Pancake Sorting/969. Pancake Sorting.go @@ -11,8 +11,8 @@ func pancakeSort(A []int) []int { for right > 0 { idx := find(A, right) if idx != right-1 { - reverse_(A, 0, idx) - reverse_(A, 0, right-1) + reverse969(A, 0, idx) + reverse969(A, 0, right-1) ans = append(ans, idx+1, right) } right-- @@ -21,7 +21,7 @@ func pancakeSort(A []int) []int { return ans } -func reverse_(nums []int, l, r int) { +func reverse969(nums []int, l, r int) { for l < r { nums[l], nums[r] = nums[r], nums[l] l++ diff --git a/Algorithms/0973. K Closest Points to Origin/973. K Closest Points to Origin.go b/Algorithms/0973. K Closest Points to Origin/973. K Closest Points to Origin.go index 31496106..46d9de11 100644 --- a/Algorithms/0973. K Closest Points to Origin/973. K Closest Points to Origin.go +++ b/Algorithms/0973. K Closest Points to Origin/973. K Closest Points to Origin.go @@ -2,7 +2,8 @@ package leetcode import "sort" -func kClosest(points [][]int, K int) [][]int { +// KClosest define +func KClosest(points [][]int, K int) [][]int { sort.Slice(points, func(i, j int) bool { return points[i][0]*points[i][0]+points[i][1]*points[i][1] < points[j][0]*points[j][0]+points[j][1]*points[j][1] diff --git a/Algorithms/0973. K Closest Points to Origin/973. K Closest Points to Origin_test.go b/Algorithms/0973. K Closest Points to Origin/973. K Closest Points to Origin_test.go index b953c873..ea223ffa 100644 --- a/Algorithms/0973. K Closest Points to Origin/973. K Closest Points to Origin_test.go +++ b/Algorithms/0973. K Closest Points to Origin/973. K Closest Points to Origin_test.go @@ -57,7 +57,7 @@ func Test_Problem973(t *testing.T) { for _, q := range qs { _, p := q.ans973, q.para973 - fmt.Printf("【input】:%v 【output】:%v\n", p, kClosest(p.one, p.two)) + fmt.Printf("【input】:%v 【output】:%v\n", p, KClosest(p.one, p.two)) } 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 da6680f7..03f426cb 100644 --- a/Algorithms/0976. Largest Perimeter Triangle/976. Largest Perimeter Triangle.go +++ b/Algorithms/0976. Largest Perimeter Triangle/976. Largest Perimeter Triangle.go @@ -4,8 +4,7 @@ func largestPerimeter(A []int) int { if len(A) < 3 { return 0 } - quickSort__(A, 0, len(A)-1) - + quickSort164(A, 0, len(A)-1) for i := len(A) - 1; i >= 2; i-- { if (A[i]+A[i-1] > A[i-2]) && (A[i]+A[i-2] > A[i-1]) && (A[i-2]+A[i-1] > A[i]) { return A[i] + A[i-1] + A[i-2] diff --git a/Algorithms/0977. Squares of a Sorted Array/977. Squares of a Sorted Array.go b/Algorithms/0977. Squares of a Sorted Array/977. Squares of a Sorted Array.go index 215fee71..9ded1fd2 100644 --- a/Algorithms/0977. Squares of a Sorted Array/977. Squares of a Sorted Array.go +++ b/Algorithms/0977. Squares of a Sorted Array/977. Squares of a Sorted Array.go @@ -18,7 +18,7 @@ func sortedSquares(A []int) []int { } // 解法二 -func sortedSquares_(A []int) []int { +func sortedSquares1(A []int) []int { for i, value := range A { A[i] = value * value } 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 396b587d..f5a520c0 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 @@ -52,7 +52,7 @@ type mark struct { depth int } -func isCousins_BFS(root *TreeNode, x int, y int) bool { +func isCousinsBFS(root *TreeNode, x int, y int) bool { if root == nil { return false } @@ -83,7 +83,7 @@ func isCousins_BFS(root *TreeNode, x int, y int) bool { } // 解法三 DFS -func isCousins_DFS(root *TreeNode, x int, y int) bool { +func isCousinsDFS(root *TreeNode, x int, y int) bool { var depth1, depth2, parent1, parent2 int dfsCousins(root, x, 0, -1, &parent1, &depth1) dfsCousins(root, y, 0, -1, &parent2, &depth2) diff --git a/Algorithms/0996. Number of Squareful Arrays/996. Number of Squareful Arrays.go b/Algorithms/0996. Number of Squareful Arrays/996. Number of Squareful Arrays.go index a072775d..5d28e285 100644 --- a/Algorithms/0996. Number of Squareful Arrays/996. Number of Squareful Arrays.go +++ b/Algorithms/0996. Number of Squareful Arrays/996. Number of Squareful Arrays.go @@ -11,11 +11,11 @@ func numSquarefulPerms(A []int) int { } used, p, res := make([]bool, len(A)), []int{}, [][]int{} sort.Ints(A) // 这里是去重的关键逻辑 - generatePermutation_996(A, 0, p, &res, &used) + generatePermutation996(A, 0, p, &res, &used) return len(res) } -func generatePermutation_996(nums []int, index int, p []int, res *[][]int, used *[]bool) { +func generatePermutation996(nums []int, index int, p []int, res *[][]int, used *[]bool) { if index == len(nums) { checkSquareful := true for i := 0; i < len(p)-1; i++ { @@ -41,7 +41,7 @@ func generatePermutation_996(nums []int, index int, p []int, res *[][]int, used } (*used)[i] = true p = append(p, nums[i]) - generatePermutation_996(nums, index+1, p, res, used) + generatePermutation996(nums, index+1, p, res, used) p = p[:len(p)-1] (*used)[i] = false } diff --git a/Algorithms/1003. Check If Word Is Valid After Substitutions/1003. Check If Word Is Valid After Substitutions.go b/Algorithms/1003. Check If Word Is Valid After Substitutions/1003. Check If Word Is Valid After Substitutions.go index 9dee249c..472182ac 100644 --- a/Algorithms/1003. Check If Word Is Valid After Substitutions/1003. Check If Word Is Valid After Substitutions.go +++ b/Algorithms/1003. Check If Word Is Valid After Substitutions/1003. Check If Word Is Valid After Substitutions.go @@ -1,6 +1,6 @@ package leetcode -func isValid_(S string) bool { +func isValid1003(S string) bool { if len(S) < 3 { return false } diff --git a/Algorithms/1003. Check If Word Is Valid After Substitutions/1003. Check If Word Is Valid After Substitutions_test.go b/Algorithms/1003. Check If Word Is Valid After Substitutions/1003. Check If Word Is Valid After Substitutions_test.go index 0ab277b5..d0437941 100644 --- a/Algorithms/1003. Check If Word Is Valid After Substitutions/1003. Check If Word Is Valid After Substitutions_test.go +++ b/Algorithms/1003. Check If Word Is Valid After Substitutions/1003. Check If Word Is Valid After Substitutions_test.go @@ -51,7 +51,7 @@ func Test_Problem1003(t *testing.T) { for _, q := range qs { _, p := q.ans1003, q.para1003 - fmt.Printf("【input】:%v 【output】:%v\n", p, isValid_(p.s)) + fmt.Printf("【input】:%v 【output】:%v\n", p, isValid1003(p.s)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/1021. Remove Outermost Parentheses/1021. Remove Outermost Parentheses.go b/Algorithms/1021. Remove Outermost Parentheses/1021. Remove Outermost Parentheses.go index 76ea277a..5cdb5525 100644 --- a/Algorithms/1021. Remove Outermost Parentheses/1021. Remove Outermost Parentheses.go +++ b/Algorithms/1021. Remove Outermost Parentheses/1021. Remove Outermost Parentheses.go @@ -5,9 +5,9 @@ func removeOuterParentheses(S string) string { now, current, ans := 0, "", "" for _, char := range S { if string(char) == "(" { - now += 1 + now++ } else if string(char) == ")" { - now -= 1 + now-- } current += string(char) if now == 0 { @@ -19,7 +19,7 @@ func removeOuterParentheses(S string) string { } // 解法二 -func removeOuterParentheses_(S string) string { +func removeOuterParentheses1(S string) string { stack, res, counter := []byte{}, "", 0 for i := 0; i < len(S); i++ { if counter == 0 && len(stack) == 1 && S[i] == ')' { @@ -30,7 +30,6 @@ func removeOuterParentheses_(S string) string { stack = append(stack, S[i]) continue } - if len(stack) > 0 { switch S[i] { case '(': diff --git a/Algorithms/1047. Remove All Adjacent Duplicates In String/1047. Remove All Adjacent Duplicates In String.go b/Algorithms/1047. Remove All Adjacent Duplicates In String/1047. Remove All Adjacent Duplicates In String.go index 8a7e8a29..bcc412a4 100644 --- a/Algorithms/1047. Remove All Adjacent Duplicates In String/1047. Remove All Adjacent Duplicates In String.go +++ b/Algorithms/1047. Remove All Adjacent Duplicates In String/1047. Remove All Adjacent Duplicates In String.go @@ -1,6 +1,6 @@ package leetcode -func removeDuplicates_1047(S string) string { +func removeDuplicates1047(S string) string { stack := []rune{} for _, s := range S { if len(stack) == 0 || len(stack) > 0 && stack[len(stack)-1] != s { diff --git a/Algorithms/1047. Remove All Adjacent Duplicates In String/1047. Remove All Adjacent Duplicates In String_test.go b/Algorithms/1047. Remove All Adjacent Duplicates In String/1047. Remove All Adjacent Duplicates In String_test.go index 9d875339..e57c00cf 100644 --- a/Algorithms/1047. Remove All Adjacent Duplicates In String/1047. Remove All Adjacent Duplicates In String_test.go +++ b/Algorithms/1047. Remove All Adjacent Duplicates In String/1047. Remove All Adjacent Duplicates In String_test.go @@ -36,7 +36,7 @@ func Test_Problem1047(t *testing.T) { for _, q := range qs { _, p := q.ans1047, q.para1047 - fmt.Printf("【input】:%v 【output】:%v\n", p, removeDuplicates_1047(p.s)) + fmt.Printf("【input】:%v 【output】:%v\n", p, removeDuplicates1047(p.s)) } fmt.Printf("\n\n\n") } diff --git a/Algorithms/1079. Letter Tile Possibilities/1079. Letter Tile Possibilities.go b/Algorithms/1079. Letter Tile Possibilities/1079. Letter Tile Possibilities.go index f430ac00..3b05dfa1 100644 --- a/Algorithms/1079. Letter Tile Possibilities/1079. Letter Tile Possibilities.go +++ b/Algorithms/1079. Letter Tile Possibilities/1079. Letter Tile Possibilities.go @@ -4,7 +4,7 @@ package leetcode func numTilePossibilities(tiles string) int { m := make(map[byte]int) for i := range tiles { - m[tiles[i]] += 1 + m[tiles[i]]++ } arr := make([]int, 0) for _, v := range m { @@ -18,16 +18,16 @@ func numTileDFS(arr []int) (r int) { if arr[i] == 0 { continue } - r += 1 - arr[i] -= 1 + r++ + arr[i]-- r += numTileDFS(arr) - arr[i] += 1 + arr[i]++ } return } // 解法二 DFS 暴力解法 -func numTilePossibilities_(tiles string) int { +func numTilePossibilities1(tiles string) int { res, tmp, tMap, used := 0, []byte{}, make(map[string]string, 0), make([]bool, len(tiles)) findTile([]byte(tiles), tmp, &used, 0, &res, tMap) return res