repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0500.Keyboard-Row/500. Keyboard Row.go | leetcode/0500.Keyboard-Row/500. Keyboard Row.go | package leetcode
import "strings"
func findWords500(words []string) []string {
rows := []string{"qwertyuiop", "asdfghjkl", "zxcvbnm"}
output := make([]string, 0)
for _, s := range words {
if len(s) == 0 {
continue
}
lowerS := strings.ToLower(s)
oneRow := false
for _, r := range rows {
if strings.ContainsAny(lowerS, r) {
oneRow = !oneRow
if !oneRow {
break
}
}
}
if oneRow {
output = append(output, s)
}
}
return output
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0500.Keyboard-Row/500. Keyboard Row_test.go | leetcode/0500.Keyboard-Row/500. Keyboard Row_test.go | package leetcode
import (
"fmt"
"testing"
)
type question500 struct {
para500
ans500
}
// para 是参数
// one 代表第一个参数
type para500 struct {
one []string
}
// ans 是答案
// one 代表第一个答案
type ans500 struct {
one []string
}
func Test_Problem500(t *testing.T) {
qs := []question500{
{
para500{[]string{"Hello", "Alaska", "Dad", "Peace"}},
ans500{[]string{"Alaska", "Dad"}},
},
}
fmt.Printf("------------------------Leetcode Problem 500------------------------\n")
for _, q := range qs {
_, p := q.ans500, q.para500
fmt.Printf("【input】:%v 【output】:%v\n", p, findWords500(p.one))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0199.Binary-Tree-Right-Side-View/199. Binary Tree Right Side View_test.go | leetcode/0199.Binary-Tree-Right-Side-View/199. Binary Tree Right Side View_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question199 struct {
para199
ans199
}
// para 是参数
// one 代表第一个参数
type para199 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans199 struct {
one []int
}
func Test_Problem199(t *testing.T) {
qs := []question199{
{
para199{[]int{}},
ans199{[]int{}},
},
{
para199{[]int{1}},
ans199{[]int{1}},
},
{
para199{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}},
ans199{[]int{3, 20, 7}},
},
{
para199{[]int{1, 2, 3, 4, structures.NULL, structures.NULL, 5}},
ans199{[]int{1, 3, 5}},
},
}
fmt.Printf("------------------------Leetcode Problem 199------------------------\n")
for _, q := range qs {
_, p := q.ans199, q.para199
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", rightSideView(root))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0199.Binary-Tree-Right-Side-View/199. Binary Tree Right Side View.go | leetcode/0199.Binary-Tree-Right-Side-View/199. Binary Tree Right Side View.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func rightSideView(root *TreeNode) []int {
res := []int{}
if root == nil {
return res
}
queue := []*TreeNode{root}
for len(queue) > 0 {
n := len(queue)
for i := 0; i < n; i++ {
if queue[i].Left != nil {
queue = append(queue, queue[i].Left)
}
if queue[i].Right != nil {
queue = append(queue, queue[i].Right)
}
}
res = append(res, queue[n-1].Val)
queue = queue[n:]
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0226.Invert-Binary-Tree/226. Invert Binary Tree.go | leetcode/0226.Invert-Binary-Tree/226. Invert Binary Tree.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
invertTree(root.Left)
invertTree(root.Right)
root.Left, root.Right = root.Right, root.Left
return root
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0226.Invert-Binary-Tree/226. Invert Binary Tree_test.go | leetcode/0226.Invert-Binary-Tree/226. Invert Binary Tree_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question226 struct {
para226
ans226
}
// para 是参数
// one 代表第一个参数
type para226 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans226 struct {
one []int
}
func Test_Problem226(t *testing.T) {
qs := []question226{
{
para226{[]int{}},
ans226{[]int{}},
},
{
para226{[]int{1}},
ans226{[]int{1}},
},
{
para226{[]int{4, 2, 7, 1, 3, 6, 9}},
ans226{[]int{4, 7, 2, 9, 6, 3, 1}},
},
}
fmt.Printf("------------------------Leetcode Problem 226------------------------\n")
for _, q := range qs {
_, p := q.ans226, q.para226
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", structures.Tree2ints(invertTree(root)))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0583.Delete-Operation-for-Two-Strings/583. Delete Operation for Two Strings.go | leetcode/0583.Delete-Operation-for-Two-Strings/583. Delete Operation for Two Strings.go | package leetcode
func minDistance(word1 string, word2 string) int {
dp := make([][]int, len(word1)+1)
for i := 0; i < len(word1)+1; i++ {
dp[i] = make([]int, len(word2)+1)
}
for i := 0; i < len(word1)+1; i++ {
dp[i][0] = i
}
for i := 0; i < len(word2)+1; i++ {
dp[0][i] = i
}
for i := 1; i < len(word1)+1; i++ {
for j := 1; j < len(word2)+1; j++ {
if word1[i-1] == word2[j-1] {
dp[i][j] = dp[i-1][j-1]
} else {
dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j])
}
}
}
return dp[len(word1)][len(word2)]
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0583.Delete-Operation-for-Two-Strings/583. Delete Operation for Two Strings_test.go | leetcode/0583.Delete-Operation-for-Two-Strings/583. Delete Operation for Two Strings_test.go | package leetcode
import (
"fmt"
"testing"
)
type question583 struct {
para583
ans583
}
// para 是参数
// one 代表第一个参数
type para583 struct {
word1 string
word2 string
}
// ans 是答案
// one 代表第一个答案
type ans583 struct {
one int
}
func Test_Problem583(t *testing.T) {
qs := []question583{
{
para583{"sea", "eat"},
ans583{2},
},
{
para583{"leetcode", "etco"},
ans583{4},
},
}
fmt.Printf("------------------------Leetcode Problem 583------------------------\n")
for _, q := range qs {
_, p := q.ans583, q.para583
fmt.Printf("【input】:%v 【output】:%v\n", p, minDistance(p.word1, p.word2))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0870.Advantage-Shuffle/870. Advantage Shuffle.go | leetcode/0870.Advantage-Shuffle/870. Advantage Shuffle.go | package leetcode
import "sort"
func advantageCount1(A []int, B []int) []int {
n := len(A)
sort.Ints(A)
sortedB := make([]int, n)
for i := range sortedB {
sortedB[i] = i
}
sort.Slice(sortedB, func(i, j int) bool {
return B[sortedB[i]] < B[sortedB[j]]
})
useless, i, res := make([]int, 0), 0, make([]int, n)
for _, index := range sortedB {
b := B[index]
for i < n && A[i] <= b {
useless = append(useless, A[i])
i++
}
if i < n {
res[index] = A[i]
i++
} else {
res[index] = useless[0]
useless = useless[1:]
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0870.Advantage-Shuffle/870. Advantage Shuffle_test.go | leetcode/0870.Advantage-Shuffle/870. Advantage Shuffle_test.go | package leetcode
import (
"fmt"
"testing"
)
type question870 struct {
para870
ans870
}
// para 是参数
// one 代表第一个参数
type para870 struct {
A []int
B []int
}
// ans 是答案
// one 代表第一个答案
type ans870 struct {
one []int
}
func Test_Problem870(t *testing.T) {
qs := []question870{
{
para870{[]int{2, 7, 11, 15}, []int{1, 10, 4, 11}},
ans870{[]int{2, 11, 7, 15}},
},
{
para870{[]int{12, 24, 8, 32}, []int{13, 25, 32, 11}},
ans870{[]int{24, 32, 8, 12}},
},
}
fmt.Printf("------------------------Leetcode Problem 870------------------------\n")
for _, q := range qs {
_, p := q.ans870, q.para870
fmt.Printf("【input】:%v 【output】:%v\n", p, advantageCount1(p.A, p.B))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1720.Decode-XORed-Array/1720. Decode XORed Array_test.go | leetcode/1720.Decode-XORed-Array/1720. Decode XORed Array_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1720 struct {
para1720
ans1720
}
// para 是参数
// one 代表第一个参数
type para1720 struct {
encoded []int
first int
}
// ans 是答案
// one 代表第一个答案
type ans1720 struct {
one []int
}
func Test_Problem1720(t *testing.T) {
qs := []question1720{
{
para1720{[]int{1, 2, 3}, 1},
ans1720{[]int{1, 0, 2, 1}},
},
{
para1720{[]int{6, 2, 7, 3}, 4},
ans1720{[]int{4, 2, 0, 7, 4}},
},
}
fmt.Printf("------------------------Leetcode Problem 1720------------------------\n")
for _, q := range qs {
_, p := q.ans1720, q.para1720
fmt.Printf("【input】:%v 【output】:%v\n", p, decode(p.encoded, p.first))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1720.Decode-XORed-Array/1720. Decode XORed Array.go | leetcode/1720.Decode-XORed-Array/1720. Decode XORed Array.go | package leetcode
func decode(encoded []int, first int) []int {
arr := make([]int, len(encoded)+1)
arr[0] = first
for i, val := range encoded {
arr[i+1] = arr[i] ^ val
}
return arr
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0632.Smallest-Range-Covering-Elements-from-K-Lists/632. Smallest Range Covering Elements from K Lists_test.go | leetcode/0632.Smallest-Range-Covering-Elements-from-K-Lists/632. Smallest Range Covering Elements from K Lists_test.go | package leetcode
import (
"fmt"
"testing"
)
type question632 struct {
para632
ans632
}
// para 是参数
// one 代表第一个参数
type para632 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans632 struct {
one []int
}
func Test_Problem632(t *testing.T) {
qs := []question632{
{
para632{[][]int{{4, 10, 15, 24, 26}, {0, 9, 12, 20}, {5, 18, 22, 30}}},
ans632{[]int{20, 24}},
},
}
fmt.Printf("------------------------Leetcode Problem 632------------------------\n")
for _, q := range qs {
_, p := q.ans632, q.para632
fmt.Printf("【input】:%v 【output】:%v\n", p, smallestRange(p.one))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0632.Smallest-Range-Covering-Elements-from-K-Lists/632. Smallest Range Covering Elements from K Lists.go | leetcode/0632.Smallest-Range-Covering-Elements-from-K-Lists/632. Smallest Range Covering Elements from K Lists.go | package leetcode
import (
"math"
"sort"
)
func smallestRange(nums [][]int) []int {
numList, left, right, count, freqMap, res, length := []element{}, 0, -1, 0, map[int]int{}, make([]int, 2), math.MaxInt64
for i, ns := range nums {
for _, v := range ns {
numList = append(numList, element{val: v, index: i})
}
}
sort.Sort(SortByVal{numList})
for left < len(numList) {
if right+1 < len(numList) && count < len(nums) {
right++
if freqMap[numList[right].index] == 0 {
count++
}
freqMap[numList[right].index]++
} else {
if count == len(nums) {
if numList[right].val-numList[left].val < length {
length = numList[right].val - numList[left].val
res[0] = numList[left].val
res[1] = numList[right].val
}
}
freqMap[numList[left].index]--
if freqMap[numList[left].index] == 0 {
count--
}
left++
}
}
return res
}
type element struct {
val int
index int
}
type elements []element
// Len define
func (p elements) Len() int { return len(p) }
// Swap define
func (p elements) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// SortByVal define
type SortByVal struct{ elements }
// Less define
func (p SortByVal) Less(i, j int) bool {
return p.elements[i].val < p.elements[j].val
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0842.Split-Array-into-Fibonacci-Sequence/842. Split Array into Fibonacci Sequence.go | leetcode/0842.Split-Array-into-Fibonacci-Sequence/842. Split Array into Fibonacci Sequence.go | package leetcode
import (
"strconv"
"strings"
)
func splitIntoFibonacci(S string) []int {
if len(S) < 3 {
return []int{}
}
res, isComplete := []int{}, false
for firstEnd := 0; firstEnd < len(S)/2; firstEnd++ {
if S[0] == '0' && firstEnd > 0 {
break
}
first, _ := strconv.Atoi(S[:firstEnd+1])
if first >= 1<<31 { // 题目要求每个数都要小于 2^31 - 1 = 2147483647,此处剪枝很关键!
break
}
for secondEnd := firstEnd + 1; max(firstEnd, secondEnd-firstEnd) <= len(S)-secondEnd; secondEnd++ {
if S[firstEnd+1] == '0' && secondEnd-firstEnd > 1 {
break
}
second, _ := strconv.Atoi(S[firstEnd+1 : secondEnd+1])
if second >= 1<<31 { // 题目要求每个数都要小于 2^31 - 1 = 2147483647,此处剪枝很关键!
break
}
findRecursiveCheck(S, first, second, secondEnd+1, &res, &isComplete)
}
}
return res
}
// Propagate for rest of the string
func findRecursiveCheck(S string, x1 int, x2 int, left int, res *[]int, isComplete *bool) {
if x1 >= 1<<31 || x2 >= 1<<31 { // 题目要求每个数都要小于 2^31 - 1 = 2147483647,此处剪枝很关键!
return
}
if left == len(S) {
if !*isComplete {
*isComplete = true
*res = append(*res, x1)
*res = append(*res, x2)
}
return
}
if strings.HasPrefix(S[left:], strconv.Itoa(x1+x2)) && !*isComplete {
*res = append(*res, x1)
findRecursiveCheck(S, x2, x1+x2, left+len(strconv.Itoa(x1+x2)), res, isComplete)
return
}
if len(*res) > 0 && !*isComplete {
*res = (*res)[:len(*res)-1]
}
return
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0842.Split-Array-into-Fibonacci-Sequence/842. Split Array into Fibonacci Sequence_test.go | leetcode/0842.Split-Array-into-Fibonacci-Sequence/842. Split Array into Fibonacci Sequence_test.go | package leetcode
import (
"fmt"
"testing"
)
type question842 struct {
para842
ans842
}
// para 是参数
// one 代表第一个参数
type para842 struct {
one string
}
// ans 是答案
// one 代表第一个答案
type ans842 struct {
one []int
}
func Test_Problem842(t *testing.T) {
qs := []question842{
{
para842{"11235813"},
ans842{[]int{1, 1, 2, 3, 5, 8, 13}},
},
{
para842{"123456579"},
ans842{[]int{123, 456, 579}},
},
{
para842{"112358130"},
ans842{[]int{}},
},
{
para842{"0123"},
ans842{[]int{}},
},
{
para842{"1101111"},
ans842{[]int{110, 1, 111}},
},
{
para842{"539834657215398346785398346991079669377161950407626991734534318677529701785098211336528511"},
ans842{[]int{}},
},
{
para842{"3611537383985343591834441270352104793375145479938855071433500231900737525076071514982402115895535257195564161509167334647108949738176284385285234123461518508746752631120827113919550237703163294909"},
ans842{[]int{}},
},
}
fmt.Printf("------------------------Leetcode Problem 842------------------------\n")
for _, q := range qs {
_, p := q.ans842, q.para842
fmt.Printf("【input】:%v 【output】:%v\n", p, splitIntoFibonacci(p.one))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0718.Maximum-Length-of-Repeated-Subarray/718. Maximum Length of Repeated Subarray_test.go | leetcode/0718.Maximum-Length-of-Repeated-Subarray/718. Maximum Length of Repeated Subarray_test.go | package leetcode
import (
"fmt"
"testing"
)
type question718 struct {
para718
ans718
}
// para 是参数
// one 代表第一个参数
type para718 struct {
A []int
B []int
}
// ans 是答案
// one 代表第一个答案
type ans718 struct {
one int
}
func Test_Problem718(t *testing.T) {
qs := []question718{
{
para718{[]int{0, 0, 0, 0, 0}, []int{0, 0, 0, 0, 0}},
ans718{5},
},
{
para718{[]int{1, 2, 3, 2, 1}, []int{3, 2, 1, 4, 7}},
ans718{3},
},
{
para718{[]int{0, 0, 0, 0, 1}, []int{1, 0, 0, 0, 0}},
ans718{4},
},
{
para718{[]int{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, []int{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0}},
ans718{59},
},
}
fmt.Printf("------------------------Leetcode Problem 718------------------------\n")
for _, q := range qs {
_, p := q.ans718, q.para718
fmt.Printf("【input】:%v 【output】:%v\n", p, findLength(p.A, p.B))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0718.Maximum-Length-of-Repeated-Subarray/718. Maximum Length of Repeated Subarray.go | leetcode/0718.Maximum-Length-of-Repeated-Subarray/718. Maximum Length of Repeated Subarray.go | package leetcode
const primeRK = 16777619
// 解法一 二分搜索 + Rabin-Karp
func findLength(A []int, B []int) int {
low, high := 0, min(len(A), len(B))
for low < high {
mid := (low + high + 1) >> 1
if hasRepeated(A, B, mid) {
low = mid
} else {
high = mid - 1
}
}
return low
}
func min(a int, b int) int {
if a > b {
return b
}
return a
}
func hashSlice(arr []int, length int) []int {
// hash 数组里面记录 arr 比 length 长出去部分的 hash 值
hash, pl, h := make([]int, len(arr)-length+1), 1, 0
for i := 0; i < length-1; i++ {
pl *= primeRK
}
for i, v := range arr {
h = h*primeRK + v
if i >= length-1 {
hash[i-length+1] = h
h -= pl * arr[i-length+1]
}
}
return hash
}
func hasSamePrefix(A, B []int, length int) bool {
for i := 0; i < length; i++ {
if A[i] != B[i] {
return false
}
}
return true
}
func hasRepeated(A, B []int, length int) bool {
hs := hashSlice(A, length)
hashToOffset := make(map[int][]int, len(hs))
for i, h := range hs {
hashToOffset[h] = append(hashToOffset[h], i)
}
for i, h := range hashSlice(B, length) {
if offsets, ok := hashToOffset[h]; ok {
for _, offset := range offsets {
if hasSamePrefix(A[offset:], B[i:], length) {
return true
}
}
}
}
return false
}
// 解法二 DP 动态规划
func findLength1(A []int, B []int) int {
res, dp := 0, make([][]int, len(A)+1)
for i := range dp {
dp[i] = make([]int, len(B)+1)
}
for i := len(A) - 1; i >= 0; i-- {
for j := len(B) - 1; j >= 0; j-- {
if A[i] == B[j] {
dp[i][j] = dp[i+1][j+1] + 1
if dp[i][j] > res {
res = dp[i][j]
}
}
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1110.Delete-Nodes-And-Return-Forest/1110. Delete Nodes And Return Forest_test.go | leetcode/1110.Delete-Nodes-And-Return-Forest/1110. Delete Nodes And Return Forest_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question1110 struct {
para1110
ans1110
}
// para 是参数
// one 代表第一个参数
type para1110 struct {
one []int
two []int
}
// ans 是答案
// one 代表第一个答案
type ans1110 struct {
one [][]int
}
func Test_Problem1110(t *testing.T) {
qs := []question1110{
{
para1110{[]int{1, 2, 3, 4, 5, 6, 7}, []int{3, 5}},
ans1110{[][]int{{1, 2, structures.NULL, 4}, {6}, {7}}},
},
}
fmt.Printf("------------------------Leetcode Problem 1110------------------------\n")
for _, q := range qs {
_, p := q.ans1110, q.para1110
tree := structures.Ints2TreeNode(p.one)
fmt.Printf("【input】:%v 【output】:%v\n", p, delNodes(tree, p.two))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1110.Delete-Nodes-And-Return-Forest/1110. Delete Nodes And Return Forest.go | leetcode/1110.Delete-Nodes-And-Return-Forest/1110. Delete Nodes And Return Forest.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func delNodes(root *TreeNode, toDelete []int) []*TreeNode {
if root == nil {
return nil
}
res, deleteMap := []*TreeNode{}, map[int]bool{}
for _, v := range toDelete {
deleteMap[v] = true
}
dfsDelNodes(root, deleteMap, true, &res)
return res
}
func dfsDelNodes(root *TreeNode, toDel map[int]bool, isRoot bool, res *[]*TreeNode) bool {
if root == nil {
return false
}
if isRoot && !toDel[root.Val] {
*res = append(*res, root)
}
isRoot = false
if toDel[root.Val] {
isRoot = true
}
if dfsDelNodes(root.Left, toDel, isRoot, res) {
root.Left = nil
}
if dfsDelNodes(root.Right, toDel, isRoot, res) {
root.Right = nil
}
return isRoot
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/28. Find the Index of the First Occurrence in a String_test.go | leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/28. Find the Index of the First Occurrence in a String_test.go | package leetcode
import (
"fmt"
"testing"
)
type question28 struct {
para28
ans28
}
// para 是参数
// one 代表第一个参数
type para28 struct {
s string
p string
}
// ans 是答案
// one 代表第一个答案
type ans28 struct {
one int
}
func Test_Problem28(t *testing.T) {
qs := []question28{
{
para28{"abab", "ab"},
ans28{0},
},
{
para28{"hello", "ll"},
ans28{2},
},
{
para28{"", "abc"},
ans28{0},
},
{
para28{"abacbabc", "abc"},
ans28{5},
},
{
para28{"abacbabc", "abcd"},
ans28{-1},
},
{
para28{"abacbabc", ""},
ans28{0},
},
}
fmt.Printf("------------------------Leetcode Problem 28------------------------\n")
for _, q := range qs {
_, p := q.ans28, q.para28
fmt.Printf("【input】:%v 【output】:%v\n", p, strStr(p.s, p.p))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/28. Find the Index of the First Occurrence in a String.go | leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/28. Find the Index of the First Occurrence in a String.go | package leetcode
import "strings"
// 解法一
func strStr(haystack string, needle string) int {
for i := 0; ; i++ {
for j := 0; ; j++ {
if j == len(needle) {
return i
}
if i+j == len(haystack) {
return -1
}
if needle[j] != haystack[i+j] {
break
}
}
}
}
// 解法二
func strStr1(haystack string, needle string) int {
return strings.Index(haystack, needle)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0078.Subsets/78. Subsets_test.go | leetcode/0078.Subsets/78. Subsets_test.go | package leetcode
import (
"fmt"
"testing"
)
type question78 struct {
para78
ans78
}
// para 是参数
// one 代表第一个参数
type para78 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans78 struct {
one [][]int
}
func Test_Problem78(t *testing.T) {
qs := []question78{
{
para78{[]int{}},
ans78{[][]int{{}}},
},
{
para78{[]int{1, 2, 3}},
ans78{[][]int{{}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 3}, {1, 2, 3}}},
},
}
fmt.Printf("------------------------Leetcode Problem 78------------------------\n")
for _, q := range qs {
_, p := q.ans78, q.para78
fmt.Printf("【input】:%v 【output】:%v\n", p, subsets(p.one))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0078.Subsets/78. Subsets.go | leetcode/0078.Subsets/78. Subsets.go | package leetcode
import "sort"
// 解法一
func subsets(nums []int) [][]int {
c, res := []int{}, [][]int{}
for k := 0; k <= len(nums); k++ {
generateSubsets(nums, k, 0, c, &res)
}
return res
}
func generateSubsets(nums []int, k, start int, c []int, res *[][]int) {
if len(c) == k {
b := make([]int, len(c))
copy(b, c)
*res = append(*res, b)
return
}
// i will at most be n - (k - c.size()) + 1
for i := start; i < len(nums)-(k-len(c))+1; i++ {
c = append(c, nums[i])
generateSubsets(nums, k, i+1, c, res)
c = c[:len(c)-1]
}
return
}
// 解法二
func subsets1(nums []int) [][]int {
res := make([][]int, 1)
sort.Ints(nums)
for i := range nums {
for _, org := range res {
clone := make([]int, len(org), len(org)+1)
copy(clone, org)
clone = append(clone, nums[i])
res = append(res, clone)
}
}
return res
}
// 解法三:位运算的方法
func subsets2(nums []int) [][]int {
if len(nums) == 0 {
return nil
}
res := [][]int{}
sum := 1 << uint(len(nums))
for i := 0; i < sum; i++ {
stack := []int{}
tmp := i // i 从 000...000 到 111...111
for j := len(nums) - 1; j >= 0; j-- { // 遍历 i 的每一位
if tmp&1 == 1 {
stack = append([]int{nums[j]}, stack...)
}
tmp >>= 1
}
res = append(res, stack)
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1668.Maximum-Repeating-Substring/1668. Maximum Repeating Substring_test.go | leetcode/1668.Maximum-Repeating-Substring/1668. Maximum Repeating Substring_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1668 struct {
para1668
ans1668
}
// para 是参数
// one 代表第一个参数
type para1668 struct {
sequence string
word string
}
// ans 是答案
// one 代表第一个答案
type ans1668 struct {
one int
}
func Test_Problem1668(t *testing.T) {
qs := []question1668{
{
para1668{"ababc", "ab"},
ans1668{2},
},
{
para1668{"ababc", "ba"},
ans1668{1},
},
{
para1668{"ababc", "ac"},
ans1668{0},
},
}
fmt.Printf("------------------------Leetcode Problem 1668------------------------\n")
for _, q := range qs {
_, p := q.ans1668, q.para1668
fmt.Printf("【input】:%v 【output】:%v \n", p, maxRepeating(p.sequence, p.word))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1668.Maximum-Repeating-Substring/1668. Maximum Repeating Substring.go | leetcode/1668.Maximum-Repeating-Substring/1668. Maximum Repeating Substring.go | package leetcode
import (
"strings"
)
func maxRepeating(sequence string, word string) int {
for i := len(sequence) / len(word); i >= 0; i-- {
tmp := ""
for j := 0; j < i; j++ {
tmp += word
}
if strings.Contains(sequence, tmp) {
return i
}
}
return 0
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0815.Bus-Routes/815. Bus Routes.go | leetcode/0815.Bus-Routes/815. Bus Routes.go | package leetcode
func numBusesToDestination(routes [][]int, S int, T int) int {
if S == T {
return 0
}
// vertexMap 中 key 是站点,value 是公交车数组,代表这些公交车路线可以到达此站点
vertexMap, visited, queue, res := map[int][]int{}, make([]bool, len(routes)), []int{}, 0
for i := 0; i < len(routes); i++ {
for _, v := range routes[i] {
tmp := vertexMap[v]
tmp = append(tmp, i)
vertexMap[v] = tmp
}
}
queue = append(queue, S)
for len(queue) > 0 {
res++
qlen := len(queue)
for i := 0; i < qlen; i++ {
vertex := queue[0]
queue = queue[1:]
for _, bus := range vertexMap[vertex] {
if visited[bus] == true {
continue
}
visited[bus] = true
for _, v := range routes[bus] {
if v == T {
return res
}
queue = append(queue, v)
}
}
}
}
return -1
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0815.Bus-Routes/815. Bus Routes_test.go | leetcode/0815.Bus-Routes/815. Bus Routes_test.go | package leetcode
import (
"fmt"
"testing"
)
type question815 struct {
para815
ans815
}
// para 是参数
// one 代表第一个参数
type para815 struct {
r [][]int
s int
t int
}
// ans 是答案
// one 代表第一个答案
type ans815 struct {
one int
}
func Test_Problem815(t *testing.T) {
qs := []question815{
{
para815{[][]int{{1, 2, 7}, {3, 6, 7}}, 1, 6},
ans815{2},
},
}
fmt.Printf("------------------------Leetcode Problem 815------------------------\n")
for _, q := range qs {
_, p := q.ans815, q.para815
fmt.Printf("【input】:%v 【output】:%v\n", p, numBusesToDestination(p.r, p.s, p.t))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0724.Find-Pivot-Index/724. Find Pivot Index_test.go | leetcode/0724.Find-Pivot-Index/724. Find Pivot Index_test.go | package leetcode
import (
"fmt"
"testing"
)
type question724 struct {
para724
ans724
}
// para 是参数
// one 代表第一个参数
type para724 struct {
nums []int
}
// ans 是答案
// one 代表第一个答案
type ans724 struct {
n int
}
func Test_Problem724(t *testing.T) {
qs := []question724{
{
para724{[]int{1, 7, 3, 6, 5, 6}},
ans724{3},
},
{
para724{[]int{1, 2, 3}},
ans724{-1},
},
{
para724{[]int{-1, -1, -1, -1, -1, -1}},
ans724{-1},
},
{
para724{[]int{-1, -1, -1, -1, -1, 0}},
ans724{2},
},
{
para724{[]int{1}},
ans724{0},
},
{
para724{[]int{}},
ans724{-1},
},
}
fmt.Printf("------------------------Leetcode Problem 724------------------------\n")
for _, q := range qs {
_, p := q.ans724, q.para724
fmt.Printf("【input】:%v 【output】:%v\n", p, pivotIndex(p.nums))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0724.Find-Pivot-Index/724. Find Pivot Index.go | leetcode/0724.Find-Pivot-Index/724. Find Pivot Index.go | package leetcode
// 2 * leftSum + num[i] = sum
// 时间: O(n)
// 空间: O(1)
func pivotIndex(nums []int) int {
if len(nums) <= 0 {
return -1
}
var sum, leftSum int
for _, num := range nums {
sum += num
}
for index, num := range nums {
if leftSum*2+num == sum {
return index
}
leftSum += num
}
return -1
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0212.Word-Search-II/212. Word Search II_test.go | leetcode/0212.Word-Search-II/212. Word Search II_test.go | package leetcode
import (
"fmt"
"testing"
)
type question212 struct {
para212
ans212
}
// para 是参数
// one 代表第一个参数
type para212 struct {
b [][]byte
word []string
}
// ans 是答案
// one 代表第一个答案
type ans212 struct {
one []string
}
func Test_Problem212(t *testing.T) {
qs := []question212{
{
para212{[][]byte{
{'A', 'B', 'C', 'E'},
{'S', 'F', 'C', 'S'},
{'A', 'D', 'E', 'E'},
}, []string{"ABCCED", "SEE", "ABCB"}},
ans212{[]string{"ABCCED", "SEE"}},
},
{
para212{[][]byte{
{'o', 'a', 'a', 'n'},
{'e', 't', 'a', 'e'},
{'i', 'h', 'k', 'r'},
{'i', 'f', 'l', 'v'},
}, []string{"oath", "pea", "eat", "rain"}},
ans212{[]string{"oath", "eat"}},
},
}
fmt.Printf("------------------------Leetcode Problem 212------------------------\n")
for _, q := range qs {
_, p := q.ans212, q.para212
fmt.Printf("【input】:%v 【output】:%v\n\n\n", p, findWords(p.b, p.word))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0212.Word-Search-II/212. Word Search II.go | leetcode/0212.Word-Search-II/212. Word Search II.go | package leetcode
func findWords(board [][]byte, words []string) []string {
res := []string{}
for _, v := range words {
if exist(board, v) {
res = append(res, v)
}
}
return res
}
// these is 79 solution
var dir = [][]int{
{-1, 0},
{0, 1},
{1, 0},
{0, -1},
}
func exist(board [][]byte, word string) bool {
visited := make([][]bool, len(board))
for i := 0; i < len(visited); i++ {
visited[i] = make([]bool, len(board[0]))
}
for i, v := range board {
for j := range v {
if searchWord(board, visited, word, 0, i, j) {
return true
}
}
}
return false
}
func isInBoard(board [][]byte, x, y int) bool {
return x >= 0 && x < len(board) && y >= 0 && y < len(board[0])
}
func searchWord(board [][]byte, visited [][]bool, word string, index, x, y int) bool {
if index == len(word)-1 {
return board[x][y] == word[index]
}
if board[x][y] == word[index] {
visited[x][y] = true
for i := 0; i < 4; i++ {
nx := x + dir[i][0]
ny := y + dir[i][1]
if isInBoard(board, nx, ny) && !visited[nx][ny] && searchWord(board, visited, word, index+1, nx, ny) {
return true
}
}
visited[x][y] = false
}
return false
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0839.Similar-String-Groups/839. Similar String Groups_test.go | leetcode/0839.Similar-String-Groups/839. Similar String Groups_test.go | package leetcode
import (
"fmt"
"testing"
)
type question839 struct {
para839
ans839
}
// para 是参数
// one 代表第一个参数
type para839 struct {
one []string
}
// ans 是答案
// one 代表第一个答案
type ans839 struct {
one int
}
func Test_Problem839(t *testing.T) {
qs := []question839{
{
para839{[]string{"tars", "rats", "arts", "star"}},
ans839{2},
},
}
fmt.Printf("------------------------Leetcode Problem 839------------------------\n")
for _, q := range qs {
_, p := q.ans839, q.para839
fmt.Printf("【input】:%v 【output】:%v\n", p, numSimilarGroups(p.one))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0839.Similar-String-Groups/839. Similar String Groups.go | leetcode/0839.Similar-String-Groups/839. Similar String Groups.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/template"
)
func numSimilarGroups(A []string) int {
uf := template.UnionFind{}
uf.Init(len(A))
for i := 0; i < len(A); i++ {
for j := i + 1; j < len(A); j++ {
if isSimilar(A[i], A[j]) {
uf.Union(i, j)
}
}
}
return uf.TotalCount()
}
func isSimilar(a, b string) bool {
var n int
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
n++
if n > 2 {
return false
}
}
}
return true
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1579.Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversable/1579. Remove Max Number of Edges to Keep Graph Fully Traversable.go | leetcode/1579.Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversable/1579. Remove Max Number of Edges to Keep Graph Fully Traversable.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/template"
)
func maxNumEdgesToRemove(n int, edges [][]int) int {
alice, bob, res := template.UnionFind{}, template.UnionFind{}, len(edges)
alice.Init(n)
bob.Init(n)
for _, e := range edges {
x, y := e[1]-1, e[2]-1
if e[0] == 3 && (!(alice.Find(x) == alice.Find(y)) || !(bob.Find(x) == bob.Find(y))) {
alice.Union(x, y)
bob.Union(x, y)
res--
}
}
ufs := [2]*template.UnionFind{&alice, &bob}
for _, e := range edges {
if tp := e[0]; tp < 3 && !(ufs[tp-1].Find(e[1]-1) == ufs[tp-1].Find(e[2]-1)) {
ufs[tp-1].Union(e[1]-1, e[2]-1)
res--
}
}
if alice.TotalCount() > 1 || bob.TotalCount() > 1 {
return -1
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1579.Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversable/1579. Remove Max Number of Edges to Keep Graph Fully Traversable_test.go | leetcode/1579.Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversable/1579. Remove Max Number of Edges to Keep Graph Fully Traversable_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1579 struct {
para1579
ans1579
}
// para 是参数
// one 代表第一个参数
type para1579 struct {
n int
edges [][]int
}
// ans 是答案
// one 代表第一个答案
type ans1579 struct {
one int
}
func Test_Problem1579(t *testing.T) {
qs := []question1579{
{
para1579{4, [][]int{{3, 1, 2}, {3, 2, 3}, {1, 1, 3}, {1, 2, 4}, {1, 1, 2}, {2, 3, 4}}},
ans1579{2},
},
{
para1579{4, [][]int{{3, 1, 2}, {3, 2, 3}, {1, 1, 4}, {2, 1, 4}}},
ans1579{0},
},
{
para1579{4, [][]int{{3, 2, 3}, {1, 1, 2}, {2, 3, 4}}},
ans1579{-1},
},
}
fmt.Printf("------------------------Leetcode Problem 1579------------------------\n")
for _, q := range qs {
_, p := q.ans1579, q.para1579
fmt.Printf("【input】:%v 【output】:%v \n", p, maxNumEdgesToRemove(p.n, p.edges))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1049.Last-Stone-Weight-II/1049. Last Stone Weight II.go | leetcode/1049.Last-Stone-Weight-II/1049. Last Stone Weight II.go | package leetcode
func lastStoneWeightII(stones []int) int {
sum := 0
for _, v := range stones {
sum += v
}
n, C, dp := len(stones), sum/2, make([]int, sum/2+1)
for i := 0; i <= C; i++ {
if stones[0] <= i {
dp[i] = stones[0]
} else {
dp[i] = 0
}
}
for i := 1; i < n; i++ {
for j := C; j >= stones[i]; j-- {
dp[j] = max(dp[j], dp[j-stones[i]]+stones[i])
}
}
return sum - 2*dp[C]
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1049.Last-Stone-Weight-II/1049. Last Stone Weight II_test.go | leetcode/1049.Last-Stone-Weight-II/1049. Last Stone Weight II_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1049 struct {
para1049
ans1049
}
// para 是参数
// one 代表第一个参数
type para1049 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans1049 struct {
one int
}
func Test_Problem1049(t *testing.T) {
qs := []question1049{
{
para1049{[]int{2, 7, 4, 1, 8, 1}},
ans1049{1},
},
{
para1049{[]int{21, 26, 31, 33, 40}},
ans1049{5},
},
{
para1049{[]int{1, 2}},
ans1049{1},
},
}
fmt.Printf("------------------------Leetcode Problem 1049------------------------\n")
for _, q := range qs {
_, p := q.ans1049, q.para1049
fmt.Printf("【input】:%v 【output】:%v\n", p, lastStoneWeightII(p.one))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1675.Minimize-Deviation-in-Array/1675. Minimize Deviation in Array.go | leetcode/1675.Minimize-Deviation-in-Array/1675. Minimize Deviation in Array.go | package leetcode
func minimumDeviation(nums []int) int {
min, max := 0, 0
for i := range nums {
if nums[i]%2 == 1 {
nums[i] *= 2
}
if i == 0 {
min = nums[i]
max = nums[i]
} else if nums[i] < min {
min = nums[i]
} else if max < nums[i] {
max = nums[i]
}
}
res := max - min
for max%2 == 0 {
tmax, tmin := 0, 0
for i := range nums {
if nums[i] == max || (nums[i]%2 == 0 && min <= nums[i]/2) {
nums[i] /= 2
}
if i == 0 {
tmin = nums[i]
tmax = nums[i]
} else if nums[i] < tmin {
tmin = nums[i]
} else if tmax < nums[i] {
tmax = nums[i]
}
}
if tmax-tmin < res {
res = tmax - tmin
}
min, max = tmin, tmax
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1675.Minimize-Deviation-in-Array/1675. Minimize Deviation in Array_test.go | leetcode/1675.Minimize-Deviation-in-Array/1675. Minimize Deviation in Array_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1675 struct {
para1675
ans1675
}
// para 是参数
// one 代表第一个参数
type para1675 struct {
nums []int
}
// ans 是答案
// one 代表第一个答案
type ans1675 struct {
one int
}
func Test_Problem1675(t *testing.T) {
qs := []question1675{
{
para1675{[]int{1, 2, 4, 3}},
ans1675{1},
},
{
para1675{[]int{4, 1, 5, 20, 3}},
ans1675{3},
},
{
para1675{[]int{2, 10, 8}},
ans1675{3},
},
}
fmt.Printf("------------------------Leetcode Problem 1675------------------------\n")
for _, q := range qs {
_, p := q.ans1675, q.para1675
fmt.Printf("【input】:%v 【output】:%v\n", p, minimumDeviation(p.nums))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0884.Uncommon-Words-from-Two-Sentences/884. Uncommon Words from Two Sentences_test.go | leetcode/0884.Uncommon-Words-from-Two-Sentences/884. Uncommon Words from Two Sentences_test.go | package leetcode
import (
"fmt"
"testing"
)
type question884 struct {
para884
ans884
}
// para 是参数
// one 代表第一个参数
type para884 struct {
A string
B string
}
// ans 是答案
// one 代表第一个答案
type ans884 struct {
one []string
}
func Test_Problem884(t *testing.T) {
qs := []question884{
{
para884{"this apple is sweet", "this apple is sour"},
ans884{[]string{"sweet", "sour"}},
},
{
para884{"apple apple", "banana"},
ans884{[]string{"banana"}},
},
}
fmt.Printf("------------------------Leetcode Problem 884------------------------\n")
for _, q := range qs {
_, p := q.ans884, q.para884
fmt.Printf("【input】:%v 【output】:%v\n", p, uncommonFromSentences(p.A, p.B))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0884.Uncommon-Words-from-Two-Sentences/884. Uncommon Words from Two Sentences.go | leetcode/0884.Uncommon-Words-from-Two-Sentences/884. Uncommon Words from Two Sentences.go | package leetcode
import "strings"
func uncommonFromSentences(A string, B string) []string {
m, res := map[string]int{}, []string{}
for _, s := range []string{A, B} {
for _, word := range strings.Split(s, " ") {
m[word]++
}
}
for key := range m {
if m[key] == 1 {
res = append(res, key)
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0187.Repeated-DNA-Sequences/187. Repeated DNA Sequences_test.go | leetcode/0187.Repeated-DNA-Sequences/187. Repeated DNA Sequences_test.go | package leetcode
import (
"fmt"
"testing"
)
type question187 struct {
para187
ans187
}
// para 是参数
// one 代表第一个参数
type para187 struct {
one string
}
// ans 是答案
// one 代表第一个答案
type ans187 struct {
one []string
}
func Test_Problem187(t *testing.T) {
qs := []question187{
{
para187{"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"},
ans187{[]string{"AAAAACCCCC", "CCCCCAAAAA"}},
},
}
fmt.Printf("------------------------Leetcode Problem 187------------------------\n")
for _, q := range qs {
_, p := q.ans187, q.para187
fmt.Printf("【input】:%v 【output】:%v\n", p, findRepeatedDnaSequences(p.one))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0187.Repeated-DNA-Sequences/187. Repeated DNA Sequences.go | leetcode/0187.Repeated-DNA-Sequences/187. Repeated DNA Sequences.go | package leetcode
// 解法一
func findRepeatedDnaSequences(s string) []string {
if len(s) < 10 {
return nil
}
charMap, mp, result := map[uint8]uint32{'A': 0, 'C': 1, 'G': 2, 'T': 3}, make(map[uint32]int, 0), []string{}
var cur uint32
for i := 0; i < 9; i++ { // 前9位,忽略
cur = cur<<2 | charMap[s[i]]
}
for i := 9; i < len(s); i++ {
cur = ((cur << 2) & 0xFFFFF) | charMap[s[i]]
if mp[cur] == 0 {
mp[cur] = 1
} else if mp[cur] == 1 { // >2,重复
mp[cur] = 2
result = append(result, s[i-9:i+1])
}
}
return result
}
// 解法二
func findRepeatedDnaSequences1(s string) []string {
if len(s) < 10 {
return []string{}
}
ans, cache := make([]string, 0), make(map[string]int)
for i := 0; i <= len(s)-10; i++ {
curr := string(s[i : i+10])
if cache[curr] == 1 {
ans = append(ans, curr)
}
cache[curr]++
}
return ans
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0098.Validate-Binary-Search-Tree/98. Validate Binary Search Tree.go | leetcode/0098.Validate-Binary-Search-Tree/98. Validate Binary Search Tree.go | package leetcode
import (
"math"
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 解法一,直接按照定义比较大小,比 root 节点小的都在左边,比 root 节点大的都在右边
func isValidBST(root *TreeNode) bool {
return isValidbst(root, math.Inf(-1), math.Inf(1))
}
func isValidbst(root *TreeNode, min, max float64) bool {
if root == nil {
return true
}
v := float64(root.Val)
return v < max && v > min && isValidbst(root.Left, min, v) && isValidbst(root.Right, v, max)
}
// 解法二,把 BST 按照左中右的顺序输出到数组中,如果是 BST,则数组中的数字是从小到大有序的,如果出现逆序就不是 BST
func isValidBST1(root *TreeNode) bool {
arr := []int{}
inOrder(root, &arr)
for i := 1; i < len(arr); i++ {
if arr[i-1] >= arr[i] {
return false
}
}
return true
}
func inOrder(root *TreeNode, arr *[]int) {
if root == nil {
return
}
inOrder(root.Left, arr)
*arr = append(*arr, root.Val)
inOrder(root.Right, arr)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0098.Validate-Binary-Search-Tree/98. Validate Binary Search Tree_test.go | leetcode/0098.Validate-Binary-Search-Tree/98. Validate Binary Search Tree_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question98 struct {
para98
ans98
}
// para 是参数
// one 代表第一个参数
type para98 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans98 struct {
one bool
}
func Test_Problem98(t *testing.T) {
qs := []question98{
{
para98{[]int{10, 5, 15, structures.NULL, structures.NULL, 6, 20}},
ans98{false},
},
{
para98{[]int{}},
ans98{true},
},
{
para98{[]int{2, 1, 3}},
ans98{true},
},
{
para98{[]int{5, 1, 4, structures.NULL, structures.NULL, 3, 6}},
ans98{false},
},
}
fmt.Printf("------------------------Leetcode Problem 98------------------------\n")
for _, q := range qs {
_, p := q.ans98, q.para98
fmt.Printf("【input】:%v ", p)
rootOne := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", isValidBST(rootOne))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0775.Global-and-Local-Inversions/775. Global and Local Inversions.go | leetcode/0775.Global-and-Local-Inversions/775. Global and Local Inversions.go | package leetcode
func isIdealPermutation(A []int) bool {
for i := range A {
if abs(A[i]-i) > 1 {
return false
}
}
return true
}
func abs(a int) int {
if a < 0 {
return -a
}
return a
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0775.Global-and-Local-Inversions/775. Global and Local Inversions_test.go | leetcode/0775.Global-and-Local-Inversions/775. Global and Local Inversions_test.go | package leetcode
import (
"fmt"
"testing"
)
type question775 struct {
para775
ans775
}
// para 是参数
// one 代表第一个参数
type para775 struct {
A []int
}
// ans 是答案
// one 代表第一个答案
type ans775 struct {
one bool
}
func Test_Problem775(t *testing.T) {
qs := []question775{
{
para775{[]int{1, 0, 2}},
ans775{true},
},
{
para775{[]int{1, 2, 0}},
ans775{false},
},
}
fmt.Printf("------------------------Leetcode Problem 775------------------------\n")
for _, q := range qs {
_, p := q.ans775, q.para775
fmt.Printf("【input】:%v 【output】:%v\n", p, isIdealPermutation(p.A))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0223.Rectangle-Area/223. Rectangle Area.go | leetcode/0223.Rectangle-Area/223. Rectangle Area.go | package leetcode
func computeArea(A int, B int, C int, D int, E int, F int, G int, H int) int {
X0, Y0, X1, Y1 := max(A, E), max(B, F), min(C, G), min(D, H)
return area(A, B, C, D) + area(E, F, G, H) - area(X0, Y0, X1, Y1)
}
func area(x0, y0, x1, y1 int) int {
l, h := x1-x0, y1-y0
if l <= 0 || h <= 0 {
return 0
}
return l * h
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
func min(a int, b int) int {
if a > b {
return b
}
return a
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0223.Rectangle-Area/223. Rectangle Area_test.go | leetcode/0223.Rectangle-Area/223. Rectangle Area_test.go | package leetcode
import (
"fmt"
"testing"
)
type question223 struct {
para223
ans223
}
// para 是参数
// one 代表第一个参数
type para223 struct {
A int
B int
C int
D int
E int
F int
G int
H int
}
// ans 是答案
// one 代表第一个答案
type ans223 struct {
one int
}
func Test_Problem223(t *testing.T) {
qs := []question223{
{
para223{-3, 0, 3, 4, 0, -1, 9, 2},
ans223{45},
},
}
fmt.Printf("------------------------Leetcode Problem 223------------------------\n")
for _, q := range qs {
_, p := q.ans223, q.para223
fmt.Printf("【input】:%v 【output】:%v\n", p, computeArea(p.A, p.B, p.C, p.D, p.E, p.F, p.G, p.H))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0920.Number-of-Music-Playlists/920. Number of Music Playlists_test.go | leetcode/0920.Number-of-Music-Playlists/920. Number of Music Playlists_test.go | package leetcode
import (
"fmt"
"testing"
)
type question920 struct {
para920
ans920
}
// para 是参数
// one 代表第一个参数
type para920 struct {
N int
L int
K int
}
// ans 是答案
// one 代表第一个答案
type ans920 struct {
one int
}
func Test_Problem920(t *testing.T) {
qs := []question920{
{
para920{3, 3, 1},
ans920{6},
},
{
para920{2, 3, 0},
ans920{6},
},
{
para920{2, 3, 1},
ans920{2},
},
}
fmt.Printf("------------------------Leetcode Problem 920------------------------\n")
for _, q := range qs {
_, p := q.ans920, q.para920
fmt.Printf("【input】:%v 【output】:%v\n", p, numMusicPlaylists(p.N, p.L, p.K))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0920.Number-of-Music-Playlists/920. Number of Music Playlists.go | leetcode/0920.Number-of-Music-Playlists/920. Number of Music Playlists.go | package leetcode
func numMusicPlaylists(N int, L int, K int) int {
dp, mod := make([][]int, L+1), 1000000007
for i := 0; i < L+1; i++ {
dp[i] = make([]int, N+1)
}
dp[0][0] = 1
for i := 1; i <= L; i++ {
for j := 1; j <= N; j++ {
dp[i][j] = (dp[i-1][j-1] * (N - (j - 1))) % mod
if j > K {
dp[i][j] = (dp[i][j] + (dp[i-1][j]*(j-K))%mod) % mod
}
}
}
return dp[L][N]
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1470.Shuffle-the-Array/1470. Shuffle the Array_test.go | leetcode/1470.Shuffle-the-Array/1470. Shuffle the Array_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1470 struct {
para1470
ans1470
}
// para 是参数
// one 代表第一个参数
type para1470 struct {
nums []int
n int
}
// ans 是答案
// one 代表第一个答案
type ans1470 struct {
one []int
}
func Test_Problem1470(t *testing.T) {
qs := []question1470{
{
para1470{[]int{2, 5, 1, 3, 4, 7}, 3},
ans1470{[]int{2, 3, 5, 4, 1, 7}},
},
{
para1470{[]int{1, 2, 3, 4, 4, 3, 2, 1}, 4},
ans1470{[]int{1, 4, 2, 3, 3, 2, 4, 1}},
},
{
para1470{[]int{1, 1, 2, 2}, 2},
ans1470{[]int{1, 2, 1, 2}},
},
}
fmt.Printf("------------------------Leetcode Problem 1470------------------------\n")
for _, q := range qs {
_, p := q.ans1470, q.para1470
fmt.Printf("【input】:%v 【output】:%v \n", p, shuffle(p.nums, p.n))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1470.Shuffle-the-Array/1470. Shuffle the Array.go | leetcode/1470.Shuffle-the-Array/1470. Shuffle the Array.go | package leetcode
func shuffle(nums []int, n int) []int {
result := make([]int, 0)
for i := 0; i < n; i++ {
result = append(result, nums[i])
result = append(result, nums[n+i])
}
return result
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0494.Target-Sum/494. Target Sum_test.go | leetcode/0494.Target-Sum/494. Target Sum_test.go | package leetcode
import (
"fmt"
"testing"
)
type question494 struct {
para494
ans494
}
// para 是参数
// one 代表第一个参数
type para494 struct {
nums []int
S int
}
// ans 是答案
// one 代表第一个答案
type ans494 struct {
one int
}
func Test_Problem494(t *testing.T) {
qs := []question494{
{
para494{[]int{1, 1, 1, 1, 1}, 3},
ans494{5},
},
}
fmt.Printf("------------------------Leetcode Problem 494------------------------\n")
for _, q := range qs {
_, p := q.ans494, q.para494
fmt.Printf("【input】:%v 【output】:%v\n", p, findTargetSumWays(p.nums, p.S))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0494.Target-Sum/494. Target Sum.go | leetcode/0494.Target-Sum/494. Target Sum.go | package leetcode
// 解法一 DP
func findTargetSumWays(nums []int, S int) int {
total := 0
for _, n := range nums {
total += n
}
if S+total < 0 || S > total || (S+total)%2 == 1 {
return 0
}
target := (S + total) / 2
dp := make([]int, target+1)
dp[0] = 1
for _, n := range nums {
for i := target; i >= n; i-- {
dp[i] += dp[i-n]
}
}
return dp[target]
}
// 解法二 DFS
func findTargetSumWays1(nums []int, S int) int {
// sums[i] 存储的是后缀和 nums[i:],即从 i 到结尾的和
sums := make([]int, len(nums))
sums[len(nums)-1] = nums[len(nums)-1]
for i := len(nums) - 2; i > -1; i-- {
sums[i] = sums[i+1] + nums[i]
}
res := 0
dfsFindTargetSumWays(nums, 0, 0, S, &res, sums)
return res
}
func dfsFindTargetSumWays(nums []int, index int, curSum int, S int, res *int, sums []int) {
if index == len(nums) {
if curSum == S {
*(res) = *(res) + 1
}
return
}
// 剪枝优化:如果 sums[index] 值小于剩下需要正数的值,那么右边就算都是 + 号也无能为力了,所以这里可以剪枝了
if S-curSum > sums[index] {
return
}
dfsFindTargetSumWays(nums, index+1, curSum+nums[index], S, res, sums)
dfsFindTargetSumWays(nums, index+1, curSum-nums[index], S, res, sums)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0004.Median-of-Two-Sorted-Arrays/4. Median of Two Sorted Arrays.go | leetcode/0004.Median-of-Two-Sorted-Arrays/4. Median of Two Sorted Arrays.go | package leetcode
func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
// 假设 nums1 的长度小
if len(nums1) > len(nums2) {
return findMedianSortedArrays(nums2, nums1)
}
low, high, k, nums1Mid, nums2Mid := 0, len(nums1), (len(nums1)+len(nums2)+1)>>1, 0, 0
for low <= high {
// nums1: ……………… nums1[nums1Mid-1] | nums1[nums1Mid] ……………………
// nums2: ……………… nums2[nums2Mid-1] | nums2[nums2Mid] ……………………
nums1Mid = low + (high-low)>>1 // 分界限右侧是 mid,分界线左侧是 mid - 1
nums2Mid = k - nums1Mid
if nums1Mid > 0 && nums1[nums1Mid-1] > nums2[nums2Mid] { // nums1 中的分界线划多了,要向左边移动
high = nums1Mid - 1
} else if nums1Mid != len(nums1) && nums1[nums1Mid] < nums2[nums2Mid-1] { // nums1 中的分界线划少了,要向右边移动
low = nums1Mid + 1
} else {
// 找到合适的划分了,需要输出最终结果了
// 分为奇数偶数 2 种情况
break
}
}
midLeft, midRight := 0, 0
if nums1Mid == 0 {
midLeft = nums2[nums2Mid-1]
} else if nums2Mid == 0 {
midLeft = nums1[nums1Mid-1]
} else {
midLeft = max(nums1[nums1Mid-1], nums2[nums2Mid-1])
}
if (len(nums1)+len(nums2))&1 == 1 {
return float64(midLeft)
}
if nums1Mid == len(nums1) {
midRight = nums2[nums2Mid]
} else if nums2Mid == len(nums2) {
midRight = nums1[nums1Mid]
} else {
midRight = min(nums1[nums1Mid], nums2[nums2Mid])
}
return float64(midLeft+midRight) / 2
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
func min(a int, b int) int {
if a > b {
return b
}
return a
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0004.Median-of-Two-Sorted-Arrays/4. Median of Two Sorted Arrays_test.go | leetcode/0004.Median-of-Two-Sorted-Arrays/4. Median of Two Sorted Arrays_test.go | package leetcode
import (
"fmt"
"testing"
)
type question4 struct {
para4
ans4
}
// para 是参数
// one 代表第一个参数
type para4 struct {
nums1 []int
nums2 []int
}
// ans 是答案
// one 代表第一个答案
type ans4 struct {
one float64
}
func Test_Problem4(t *testing.T) {
qs := []question4{
{
para4{[]int{1, 3}, []int{2}},
ans4{2.0},
},
{
para4{[]int{1, 2}, []int{3, 4}},
ans4{2.5},
},
}
fmt.Printf("------------------------Leetcode Problem 4------------------------\n")
for _, q := range qs {
_, p := q.ans4, q.para4
fmt.Printf("【input】:%v 【output】:%v\n", p, findMedianSortedArrays(p.nums1, p.nums2))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0005.Longest-Palindromic-Substring/5. Longest Palindromic Substring.go | leetcode/0005.Longest-Palindromic-Substring/5. Longest Palindromic Substring.go | package leetcode
// 解法一 Manacher's algorithm,时间复杂度 O(n),空间复杂度 O(n)
func longestPalindrome(s string) string {
if len(s) < 2 {
return s
}
newS := make([]rune, 0)
newS = append(newS, '#')
for _, c := range s {
newS = append(newS, c)
newS = append(newS, '#')
}
// dp[i]: 以预处理字符串下标 i 为中心的回文半径(奇数长度时不包括中心)
// maxRight: 通过中心扩散的方式能够扩散的最右边的下标
// center: 与 maxRight 对应的中心字符的下标
// maxLen: 记录最长回文串的半径
// begin: 记录最长回文串在起始串 s 中的起始下标
dp, maxRight, center, maxLen, begin := make([]int, len(newS)), 0, 0, 1, 0
for i := 0; i < len(newS); i++ {
if i < maxRight {
// 这一行代码是 Manacher 算法的关键所在
dp[i] = min(maxRight-i, dp[2*center-i])
}
// 中心扩散法更新 dp[i]
left, right := i-(1+dp[i]), i+(1+dp[i])
for left >= 0 && right < len(newS) && newS[left] == newS[right] {
dp[i]++
left--
right++
}
// 更新 maxRight,它是遍历过的 i 的 i + dp[i] 的最大者
if i+dp[i] > maxRight {
maxRight = i + dp[i]
center = i
}
// 记录最长回文子串的长度和相应它在原始字符串中的起点
if dp[i] > maxLen {
maxLen = dp[i]
begin = (i - maxLen) / 2 // 这里要除以 2 因为有我们插入的辅助字符 #
}
}
return s[begin : begin+maxLen]
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
// 解法二 滑动窗口,时间复杂度 O(n^2),空间复杂度 O(1)
func longestPalindrome1(s string) string {
if len(s) == 0 {
return ""
}
left, right, pl, pr := 0, -1, 0, 0
for left < len(s) {
// 移动到相同字母的最右边(如果有相同字母)
for right+1 < len(s) && s[left] == s[right+1] {
right++
}
// 找到回文的边界
for left-1 >= 0 && right+1 < len(s) && s[left-1] == s[right+1] {
left--
right++
}
if right-left > pr-pl {
pl, pr = left, right
}
// 重置到下一次寻找回文的中心
left = (left+right)/2 + 1
right = left
}
return s[pl : pr+1]
}
// 解法三 中心扩散法,时间复杂度 O(n^2),空间复杂度 O(1)
func longestPalindrome2(s string) string {
res := ""
for i := 0; i < len(s); i++ {
res = maxPalindrome(s, i, i, res)
res = maxPalindrome(s, i, i+1, res)
}
return res
}
func maxPalindrome(s string, i, j int, res string) string {
sub := ""
for i >= 0 && j < len(s) && s[i] == s[j] {
sub = s[i : j+1]
i--
j++
}
if len(res) < len(sub) {
return sub
}
return res
}
// 解法四 DP,时间复杂度 O(n^2),空间复杂度 O(n^2)
func longestPalindrome3(s string) string {
res, dp := "", make([][]bool, len(s))
for i := 0; i < len(s); i++ {
dp[i] = make([]bool, len(s))
}
for i := len(s) - 1; i >= 0; i-- {
for j := i; j < len(s); j++ {
dp[i][j] = (s[i] == s[j]) && ((j-i < 3) || dp[i+1][j-1])
if dp[i][j] && (res == "" || j-i+1 > len(res)) {
res = s[i : j+1]
}
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0005.Longest-Palindromic-Substring/5. Longest Palindromic Substring_test.go | leetcode/0005.Longest-Palindromic-Substring/5. Longest Palindromic Substring_test.go | package leetcode
import (
"fmt"
"testing"
)
type question5 struct {
para5
ans5
}
// para 是参数
// one 代表第一个参数
type para5 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans5 struct {
one string
}
func Test_Problem5(t *testing.T) {
qs := []question5{
{
para5{"babad"},
ans5{"bab"},
},
{
para5{"cbbd"},
ans5{"bb"},
},
{
para5{"a"},
ans5{"a"},
},
{
para5{"ac"},
ans5{"a"},
},
{
para5{"aa"},
ans5{"aa"},
},
{
para5{"ajgiljtperkvubjmdsefcylksrxtftqrehoitdgdtttswwttmfuvwgwrruuqmxttzsbmuhgfaoueumvbhajqsaxkkihjwevzzedizmrsmpxqavyryklbotwzngxscvyuqjkkaotitddlhhnutmotupwuwyltebtsdfssbwayuxrbgihmtphshdslktvsjadaykyjivbzhwujcdvzdxxfiixnzrmusqvwujjmxhbqbdpauacnzojnzxxgrkmupadfcsujkcwajsgintahwgbjnvjqubcxajdyyapposrkpqtpqfjcvbhlmwfutgognqxgaukpmdyaxghgoqkqnigcllachmwzrazwhpppmsodvxilrccfqgpkmdqhoorxpyjsrtbeeidsinpeyxxpsjnymxkouskyhenzgieybwkgzrhhrzgkwbyeigznehyksuokxmynjspxxyepnisdieebtrsjypxroohqdmkpgqfccrlixvdosmppphwzarzwmhcallcginqkqoghgxaydmpkuagxqngogtufwmlhbvcjfqptqpkrsoppayydjaxcbuqjvnjbgwhatnigsjawckjuscfdapumkrgxxznjozncauapdbqbhxmjjuwvqsumrznxiifxxdzvdcjuwhzbvijykyadajsvtklsdhshptmhigbrxuyawbssfdstbetlywuwputomtunhhlddtitoakkjquyvcsxgnzwtoblkyryvaqxpmsrmzidezzvewjhikkxasqjahbvmueuoafghumbszttxmquurrwgwvufmttwwstttdgdtioherqtftxrsklycfesdmjbuvkreptjligja"},
ans5{"ajgiljtperkvubjmdsefcylksrxtftqrehoitdgdtttswwttmfuvwgwrruuqmxttzsbmuhgfaoueumvbhajqsaxkkihjwevzzedizmrsmpxqavyryklbotwzngxscvyuqjkkaotitddlhhnutmotupwuwyltebtsdfssbwayuxrbgihmtphshdslktvsjadaykyjivbzhwujcdvzdxxfiixnzrmusqvwujjmxhbqbdpauacnzojnzxxgrkmupadfcsujkcwajsgintahwgbjnvjqubcxajdyyapposrkpqtpqfjcvbhlmwfutgognqxgaukpmdyaxghgoqkqnigcllachmwzrazwhpppmsodvxilrccfqgpkmdqhoorxpyjsrtbeeidsinpeyxxpsjnymxkouskyhenzgieybwkgzrhhrzgkwbyeigznehyksuokxmynjspxxyepnisdieebtrsjypxroohqdmkpgqfccrlixvdosmppphwzarzwmhcallcginqkqoghgxaydmpkuagxqngogtufwmlhbvcjfqptqpkrsoppayydjaxcbuqjvnjbgwhatnigsjawckjuscfdapumkrgxxznjozncauapdbqbhxmjjuwvqsumrznxiifxxdzvdcjuwhzbvijykyadajsvtklsdhshptmhigbrxuyawbssfdstbetlywuwputomtunhhlddtitoakkjquyvcsxgnzwtoblkyryvaqxpmsrmzidezzvewjhikkxasqjahbvmueuoafghumbszttxmquurrwgwvufmttwwstttdgdtioherqtftxrsklycfesdmjbuvkreptjligja"},
},
}
fmt.Printf("------------------------Leetcode Problem 5------------------------\n")
for _, q := range qs {
_, p := q.ans5, q.para5
fmt.Printf("【input】:%v 【output】:%v\n", p, longestPalindrome(p.s))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0820.Short-Encoding-of-Words/820. Short Encoding of Words_test.go | leetcode/0820.Short-Encoding-of-Words/820. Short Encoding of Words_test.go | package leetcode
import (
"fmt"
"testing"
)
type question820 struct {
para820
ans820
}
// para 是参数
// one 代表第一个参数
type para820 struct {
words []string
}
// ans 是答案
// one 代表第一个答案
type ans820 struct {
one int
}
func Test_Problem820(t *testing.T) {
qs := []question820{
{
para820{[]string{"time", "me", "bell"}},
ans820{10},
},
{
para820{[]string{"t"}},
ans820{2},
},
}
fmt.Printf("------------------------Leetcode Problem 820------------------------\n")
for _, q := range qs {
_, p := q.ans820, q.para820
fmt.Printf("【input】:%v 【output】:%v\n", p, minimumLengthEncoding(p.words))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0820.Short-Encoding-of-Words/820. Short Encoding of Words.go | leetcode/0820.Short-Encoding-of-Words/820. Short Encoding of Words.go | package leetcode
// 解法一 暴力
func minimumLengthEncoding(words []string) int {
res, m := 0, map[string]bool{}
for _, w := range words {
m[w] = true
}
for w := range m {
for i := 1; i < len(w); i++ {
delete(m, w[i:])
}
}
for w := range m {
res += len(w) + 1
}
return res
}
// 解法二 Trie
type node struct {
value byte
sub []*node
}
func (t *node) has(b byte) (*node, bool) {
if t == nil {
return nil, false
}
for i := range t.sub {
if t.sub[i] != nil && t.sub[i].value == b {
return t.sub[i], true
}
}
return nil, false
}
func (t *node) isLeaf() bool {
if t == nil {
return false
}
return len(t.sub) == 0
}
func (t *node) add(s []byte) {
now := t
for i := len(s) - 1; i > -1; i-- {
if v, ok := now.has(s[i]); ok {
now = v
continue
}
temp := new(node)
temp.value = s[i]
now.sub = append(now.sub, temp)
now = temp
}
}
func (t *node) endNodeOf(s []byte) *node {
now := t
for i := len(s) - 1; i > -1; i-- {
if v, ok := now.has(s[i]); ok {
now = v
continue
}
return nil
}
return now
}
func minimumLengthEncoding1(words []string) int {
res, tree, m := 0, new(node), make(map[string]bool)
for i := range words {
if !m[words[i]] {
tree.add([]byte(words[i]))
m[words[i]] = true
}
}
for s := range m {
if tree.endNodeOf([]byte(s)).isLeaf() {
res += len(s)
res++
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1984.Minimum-Difference-Between-Highest-and-Lowest-of-K-Scores/1984.Minimum Difference Between Highest and Lowest of K Scores_test.go | leetcode/1984.Minimum-Difference-Between-Highest-and-Lowest-of-K-Scores/1984.Minimum Difference Between Highest and Lowest of K Scores_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1984 struct {
para1984
ans1984
}
// para 是参数
type para1984 struct {
nums []int
k int
}
// ans 是答案
type ans1984 struct {
ans int
}
func Test_Problem1984(t *testing.T) {
qs := []question1984{
{
para1984{[]int{90}, 1},
ans1984{0},
},
{
para1984{[]int{9, 4, 1, 7}, 2},
ans1984{2},
},
}
fmt.Printf("------------------------Leetcode Problem 1984------------------------\n")
for _, q := range qs {
_, p := q.ans1984, q.para1984
fmt.Printf("【input】:%v ", p)
fmt.Printf("【output】:%v \n", minimumDifference(p.nums, p.k))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1984.Minimum-Difference-Between-Highest-and-Lowest-of-K-Scores/1984.Minimum Difference Between Highest and Lowest of K Scores.go | leetcode/1984.Minimum-Difference-Between-Highest-and-Lowest-of-K-Scores/1984.Minimum Difference Between Highest and Lowest of K Scores.go | package leetcode
import "sort"
func minimumDifference(nums []int, k int) int {
sort.Ints(nums)
minDiff := 100000 + 1
for i := 0; i < len(nums); i++ {
if i+k-1 >= len(nums) {
break
}
diff := nums[i+k-1] - nums[i]
if diff < minDiff {
minDiff = diff
}
}
return minDiff
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0524.Longest-Word-in-Dictionary-through-Deleting/524. Longest Word in Dictionary through Deleting.go | leetcode/0524.Longest-Word-in-Dictionary-through-Deleting/524. Longest Word in Dictionary through Deleting.go | package leetcode
func findLongestWord(s string, d []string) string {
res := ""
for i := 0; i < len(d); i++ {
pointS := 0
pointD := 0
for pointS < len(s) && pointD < len(d[i]) {
if s[pointS] == d[i][pointD] {
pointD++
}
pointS++
}
if pointD == len(d[i]) && (len(res) < len(d[i]) || (len(res) == len(d[i]) && res > d[i])) {
res = d[i]
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0524.Longest-Word-in-Dictionary-through-Deleting/524. Longest Word in Dictionary through Deleting_test.go | leetcode/0524.Longest-Word-in-Dictionary-through-Deleting/524. Longest Word in Dictionary through Deleting_test.go | package leetcode
import (
"fmt"
"testing"
)
type question524 struct {
para524
ans524
}
// para 是参数
// one 代表第一个参数
type para524 struct {
s string
one []string
}
// ans 是答案
// one 代表第一个答案
type ans524 struct {
one string
}
func Test_Problem524(t *testing.T) {
qs := []question524{
{
para524{"abpcplea", []string{"ale", "apple", "monkey", "plea"}},
ans524{"apple"},
},
{
para524{"abpcplea", []string{"a", "b", "c"}},
ans524{"a"},
},
{
para524{"abpcplea", []string{"aaaaa", "b", "c"}},
ans524{"b"},
},
{
para524{"bab", []string{"ba", "ab", "a", "b"}},
ans524{"ab"},
},
{
para524{"aewfafwafjlwajflwajflwafj", []string{"apple", "ewaf", "awefawfwaf", "awef", "awefe", "ewafeffewafewf"}},
ans524{"ewaf"},
},
}
fmt.Printf("------------------------Leetcode Problem 524------------------------\n")
for _, q := range qs {
_, p := q.ans524, q.para524
fmt.Printf("【input】:%v 【output】:%v\n", p, findLongestWord(p.s, p.one))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0700.Search-in-a-Binary-Search-Tree/700.Search in a Binary Search Tree.go | leetcode/0700.Search-in-a-Binary-Search-Tree/700.Search in a Binary Search Tree.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func searchBST(root *TreeNode, val int) *TreeNode {
if root == nil {
return nil
}
if root.Val == val {
return root
} else if root.Val < val {
return searchBST(root.Right, val)
} else {
return searchBST(root.Left, val)
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0700.Search-in-a-Binary-Search-Tree/700.Search in a Binary Search Tree_test.go | leetcode/0700.Search-in-a-Binary-Search-Tree/700.Search in a Binary Search Tree_test.go | package leetcode
import (
"fmt"
"testing"
)
type question700 struct {
para700
ans700
}
// para 是参数
type para700 struct {
root *TreeNode
val int
}
// ans 是答案
type ans700 struct {
ans *TreeNode
}
func Test_Problem700(t *testing.T) {
qs := []question700{
{
para700{&TreeNode{Val: 4,
Left: &TreeNode{Val: 2, Left: &TreeNode{Val: 1, Left: nil, Right: nil}, Right: &TreeNode{Val: 3, Left: nil, Right: nil}},
Right: &TreeNode{Val: 7, Left: nil, Right: nil}},
2},
ans700{&TreeNode{Val: 2, Left: &TreeNode{Val: 1, Left: nil, Right: nil}, Right: &TreeNode{Val: 3, Left: nil, Right: nil}}},
},
{
para700{&TreeNode{Val: 4,
Left: &TreeNode{Val: 2, Left: &TreeNode{Val: 1, Left: nil, Right: nil}, Right: &TreeNode{Val: 3, Left: nil, Right: nil}},
Right: &TreeNode{Val: 7, Left: nil, Right: nil}},
5},
ans700{nil},
},
}
fmt.Printf("------------------------Leetcode Problem 700------------------------\n")
for _, q := range qs {
_, p := q.ans700, q.para700
fmt.Printf("【input】:%v 【output】:%v\n", p, searchBST(p.root, p.val))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0012.Integer-to-Roman/12. Integer to Roman.go | leetcode/0012.Integer-to-Roman/12. Integer to Roman.go | package leetcode
func intToRoman(num int) string {
values := []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
symbols := []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}
res, i := "", 0
for num != 0 {
for values[i] > num {
i++
}
num -= values[i]
res += symbols[i]
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0012.Integer-to-Roman/12. Integer to Roman_test.go | leetcode/0012.Integer-to-Roman/12. Integer to Roman_test.go | package leetcode
import (
"fmt"
"testing"
)
type question12 struct {
para12
ans12
}
// para 是参数
// one 代表第一个参数
type para12 struct {
one int
}
// ans 是答案
// one 代表第一个答案
type ans12 struct {
one string
}
func Test_Problem12(t *testing.T) {
qs := []question12{
{
para12{3},
ans12{"III"},
},
{
para12{4},
ans12{"IV"},
},
{
para12{9},
ans12{"IX"},
},
{
para12{58},
ans12{"LVIII"},
},
{
para12{1994},
ans12{"MCMXCIV"},
},
{
para12{123},
ans12{"CXXIII"},
},
{
para12{120},
ans12{"CXX"},
},
}
fmt.Printf("------------------------Leetcode Problem 12------------------------\n")
for _, q := range qs {
_, p := q.ans12, q.para12
fmt.Printf("【input】:%v 【output】:%v\n", p.one, intToRoman(p.one))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0154.Find-Minimum-in-Rotated-Sorted-Array-II/154. Find Minimum in Rotated Sorted Array II_test.go | leetcode/0154.Find-Minimum-in-Rotated-Sorted-Array-II/154. Find Minimum in Rotated Sorted Array II_test.go | package leetcode
import (
"fmt"
"testing"
)
type question154 struct {
para154
ans154
}
// para 是参数
// one 代表第一个参数
type para154 struct {
nums []int
}
// ans 是答案
// one 代表第一个答案
type ans154 struct {
one int
}
func Test_Problem154(t *testing.T) {
qs := []question154{
{
para154{[]int{10, 2, 10, 10, 10, 10}},
ans154{2},
},
{
para154{[]int{1, 1}},
ans154{1},
},
{
para154{[]int{2, 2, 2, 0, 1}},
ans154{0},
},
{
para154{[]int{5, 1, 2, 3, 4}},
ans154{1},
},
{
para154{[]int{1}},
ans154{1},
},
{
para154{[]int{1, 2}},
ans154{1},
},
{
para154{[]int{2, 1}},
ans154{1},
},
{
para154{[]int{2, 3, 1}},
ans154{1},
},
{
para154{[]int{1, 2, 3}},
ans154{1},
},
{
para154{[]int{3, 4, 5, 1, 2}},
ans154{1},
},
{
para154{[]int{4, 5, 6, 7, 0, 1, 2}},
ans154{0},
},
}
fmt.Printf("------------------------Leetcode Problem 154------------------------\n")
for _, q := range qs {
_, p := q.ans154, q.para154
fmt.Printf("【input】:%v 【output】:%v\n", p, findMin154(p.nums))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0154.Find-Minimum-in-Rotated-Sorted-Array-II/154. Find Minimum in Rotated Sorted Array II.go | leetcode/0154.Find-Minimum-in-Rotated-Sorted-Array-II/154. Find Minimum in Rotated Sorted Array II.go | package leetcode
func findMin154(nums []int) int {
low, high := 0, len(nums)-1
for low < high {
if nums[low] < nums[high] {
return nums[low]
}
mid := low + (high-low)>>1
if nums[mid] > nums[low] {
low = mid + 1
} else if nums[mid] == nums[low] {
low++
} else {
high = mid
}
}
return nums[low]
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0830.Positions-of-Large-Groups/830. Positions of Large Groups_test.go | leetcode/0830.Positions-of-Large-Groups/830. Positions of Large Groups_test.go | package leetcode
import (
"fmt"
"testing"
)
type question830 struct {
para830
ans830
}
// para 是参数
// one 代表第一个参数
type para830 struct {
S string
}
// ans 是答案
// one 代表第一个答案
type ans830 struct {
one [][]int
}
func Test_Problem830(t *testing.T) {
qs := []question830{
{
para830{"abbxxxxzzy"},
ans830{[][]int{{3, 6}}},
},
{
para830{"abc"},
ans830{[][]int{{}}},
},
{
para830{"abcdddeeeeaabbbcd"},
ans830{[][]int{{3, 5}, {6, 9}, {12, 14}}},
},
{
para830{"aba"},
ans830{[][]int{{}}},
},
}
fmt.Printf("------------------------Leetcode Problem 830------------------------\n")
for _, q := range qs {
_, p := q.ans830, q.para830
fmt.Printf("【input】:%v 【output】:%v\n", p, largeGroupPositions(p.S))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0830.Positions-of-Large-Groups/830. Positions of Large Groups.go | leetcode/0830.Positions-of-Large-Groups/830. Positions of Large Groups.go | package leetcode
func largeGroupPositions(S string) [][]int {
res, end := [][]int{}, 0
for end < len(S) {
start, str := end, S[end]
for end < len(S) && S[end] == str {
end++
}
if end-start >= 3 {
res = append(res, []int{start, end - 1})
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0554.Brick-Wall/554. Brick Wall.go | leetcode/0554.Brick-Wall/554. Brick Wall.go | package leetcode
func leastBricks(wall [][]int) int {
m := make(map[int]int)
for _, row := range wall {
sum := 0
for i := 0; i < len(row)-1; i++ {
sum += row[i]
m[sum]++
}
}
max := 0
for _, v := range m {
if v > max {
max = v
}
}
return len(wall) - max
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0554.Brick-Wall/554. Brick Wall_test.go | leetcode/0554.Brick-Wall/554. Brick Wall_test.go | package leetcode
import (
"fmt"
"testing"
)
type question554 struct {
para554
ans554
}
// para 是参数
// one 代表第一个参数
type para554 struct {
wall [][]int
}
// ans 是答案
// one 代表第一个答案
type ans554 struct {
one int
}
func Test_Problem554(t *testing.T) {
qs := []question554{
{
para554{[][]int{{1, 2, 2, 1}, {3, 1, 2}, {1, 3, 2}, {2, 4}, {3, 1, 2}, {1, 3, 1, 1}}},
ans554{2},
},
{
para554{[][]int{{1}, {1}, {1}}},
ans554{3},
},
{
para554{[][]int{{1, 1, 0}, {1, 1, 0}, {0, 0, 1}}},
ans554{1},
},
{
para554{[][]int{{1, 1, 0}, {1, 1, 1}, {0, 1, 1}}},
ans554{0},
},
}
fmt.Printf("------------------------Leetcode Problem 554------------------------\n")
for _, q := range qs {
_, p := q.ans554, q.para554
fmt.Printf("【input】:%v 【output】:%v\n", p, leastBricks(p.wall))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0633.Sum-of-Square-Numbers/633. Sum of Square Numbers.go | leetcode/0633.Sum-of-Square-Numbers/633. Sum of Square Numbers.go | package leetcode
import "math"
func judgeSquareSum(c int) bool {
low, high := 0, int(math.Sqrt(float64(c)))
for low <= high {
if low*low+high*high < c {
low++
} else if low*low+high*high > c {
high--
} else {
return true
}
}
return false
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0633.Sum-of-Square-Numbers/633. Sum of Square Numbers_test.go | leetcode/0633.Sum-of-Square-Numbers/633. Sum of Square Numbers_test.go | package leetcode
import (
"fmt"
"testing"
)
type question633 struct {
para633
ans633
}
// para 是参数
// one 代表第一个参数
type para633 struct {
one int
}
// ans 是答案
// one 代表第一个答案
type ans633 struct {
one bool
}
func Test_Problem633(t *testing.T) {
qs := []question633{
{
para633{1},
ans633{true},
},
{
para633{2},
ans633{true},
},
{
para633{3},
ans633{false},
},
{
para633{4},
ans633{true},
},
{
para633{5},
ans633{true},
},
{
para633{6},
ans633{false},
},
{
para633{104976},
ans633{true},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 633------------------------\n")
for _, q := range qs {
_, p := q.ans633, q.para633
fmt.Printf("【input】:%v 【output】:%v\n", p, judgeSquareSum(p.one))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0283.Move-Zeroes/283. Move Zeroes.go | leetcode/0283.Move-Zeroes/283. Move Zeroes.go | package leetcode
func moveZeroes(nums []int) {
if len(nums) == 0 {
return
}
j := 0
for i := 0; i < len(nums); i++ {
if nums[i] != 0 {
if i != j {
nums[i], nums[j] = nums[j], nums[i]
}
j++
}
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0283.Move-Zeroes/283. Move Zeroes_test.go | leetcode/0283.Move-Zeroes/283. Move Zeroes_test.go | package leetcode
import (
"fmt"
"testing"
)
type question283 struct {
para283
ans283
}
// para 是参数
// one 代表第一个参数
type para283 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans283 struct {
one []int
}
func Test_Problem283(t *testing.T) {
qs := []question283{
{
para283{[]int{1, 0, 1}},
ans283{[]int{1, 1, 0}},
},
{
para283{[]int{0, 1, 0, 3, 0, 12}},
ans283{[]int{1, 3, 12, 0, 0, 0}},
},
{
para283{[]int{0, 1, 0, 3, 0, 0, 0, 0, 1, 12}},
ans283{[]int{1, 3, 1, 12, 0, 0, 0, 0, 0}},
},
{
para283{[]int{0, 0, 0, 0, 0, 0, 0, 0, 12, 1}},
ans283{[]int{12, 1, 0, 0, 0, 0, 0, 0, 0, 0}},
},
{
para283{[]int{0, 0, 0, 0, 0}},
ans283{[]int{0, 0, 0, 0, 0}},
},
{
para283{[]int{1}},
ans283{[]int{1}},
},
}
fmt.Printf("------------------------Leetcode Problem 283------------------------\n")
for _, q := range qs {
_, p := q.ans283, q.para283
fmt.Printf("【input】:%v ", p.one)
moveZeroes(p.one)
fmt.Printf("【output】:%v\n", p.one)
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0483.Smallest-Good-Base/483. Smallest Good Base_test.go | leetcode/0483.Smallest-Good-Base/483. Smallest Good Base_test.go | package leetcode
import (
"fmt"
"testing"
)
type question483 struct {
para483
ans483
}
// para 是参数
// one 代表第一个参数
type para483 struct {
one string
}
// ans 是答案
// one 代表第一个答案
type ans483 struct {
one string
}
func Test_Problem483(t *testing.T) {
qs := []question483{
{
para483{"13"},
ans483{"3"},
},
{
para483{"4681"},
ans483{"8"},
},
{
para483{"1000000000000000000"},
ans483{"999999999999999999"},
},
{
para483{"727004545306745403"},
ans483{"727004545306745402"},
},
}
fmt.Printf("------------------------Leetcode Problem 483------------------------\n")
for _, q := range qs {
_, p := q.ans483, q.para483
fmt.Printf("【input】:%v 【output】:%v\n", p, smallestGoodBase(p.one))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0483.Smallest-Good-Base/483. Smallest Good Base.go | leetcode/0483.Smallest-Good-Base/483. Smallest Good Base.go | package leetcode
import (
"math"
"math/bits"
"strconv"
)
func smallestGoodBase(n string) string {
nVal, _ := strconv.Atoi(n)
mMax := bits.Len(uint(nVal)) - 1
for m := mMax; m > 1; m-- {
k := int(math.Pow(float64(nVal), 1/float64(m)))
mul, sum := 1, 1
for i := 0; i < m; i++ {
mul *= k
sum += mul
}
if sum == nVal {
return strconv.Itoa(k)
}
}
return strconv.Itoa(nVal - 1)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1239.Maximum-Length-of-a-Concatenated-String-with-Unique-Characters/1239. Maximum Length of a Concatenated String with Unique Characters.go | leetcode/1239.Maximum-Length-of-a-Concatenated-String-with-Unique-Characters/1239. Maximum Length of a Concatenated String with Unique Characters.go | package leetcode
import (
"math/bits"
)
func maxLength(arr []string) int {
c, res := []uint32{}, 0
for _, s := range arr {
var mask uint32
for _, c := range s {
mask = mask | 1<<(c-'a')
}
if len(s) != bits.OnesCount32(mask) { // 如果字符串本身带有重复的字符,需要排除
continue
}
c = append(c, mask)
}
dfs(c, 0, 0, &res)
return res
}
func dfs(c []uint32, index int, mask uint32, res *int) {
*res = max(*res, bits.OnesCount32(mask))
for i := index; i < len(c); i++ {
if mask&c[i] == 0 {
dfs(c, i+1, mask|c[i], res)
}
}
return
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1239.Maximum-Length-of-a-Concatenated-String-with-Unique-Characters/1239. Maximum Length of a Concatenated String with Unique Characters_test.go | leetcode/1239.Maximum-Length-of-a-Concatenated-String-with-Unique-Characters/1239. Maximum Length of a Concatenated String with Unique Characters_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1239 struct {
para1239
ans1239
}
// para 是参数
// one 代表第一个参数
type para1239 struct {
arr []string
}
// ans 是答案
// one 代表第一个答案
type ans1239 struct {
one int
}
func Test_Problem1239(t *testing.T) {
qs := []question1239{
{
para1239{[]string{"un", "iq", "ue"}},
ans1239{4},
},
{
para1239{[]string{"cha", "r", "act", "ers"}},
ans1239{6},
},
{
para1239{[]string{"abcdefghijklmnopqrstuvwxyz"}},
ans1239{26},
},
}
fmt.Printf("------------------------Leetcode Problem 1239------------------------\n")
for _, q := range qs {
_, p := q.ans1239, q.para1239
fmt.Printf("【input】:%v 【output】:%v\n", p, maxLength(p.arr))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0219.Contains-Duplicate-II/219. Contains Duplicate II.go | leetcode/0219.Contains-Duplicate-II/219. Contains Duplicate II.go | package leetcode
func containsNearbyDuplicate(nums []int, k int) bool {
if len(nums) <= 1 {
return false
}
if k <= 0 {
return false
}
record := make(map[int]bool, len(nums))
for i, n := range nums {
if _, found := record[n]; found {
return true
}
record[n] = true
if len(record) == k+1 {
delete(record, nums[i-k])
}
}
return false
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0219.Contains-Duplicate-II/219. Contains Duplicate II_test.go | leetcode/0219.Contains-Duplicate-II/219. Contains Duplicate II_test.go | package leetcode
import (
"fmt"
"testing"
)
type question219 struct {
para219
ans219
}
// para 是参数
// one 代表第一个参数
type para219 struct {
one []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans219 struct {
one bool
}
func Test_Problem219(t *testing.T) {
qs := []question219{
{
para219{[]int{1, 2, 3, 1}, 3},
ans219{true},
},
{
para219{[]int{1, 0, 0, 1}, 1},
ans219{true},
},
{
para219{[]int{1, 2, 3, 1, 2, 3}, 2},
ans219{false},
},
}
fmt.Printf("------------------------Leetcode Problem 219------------------------\n")
for _, q := range qs {
_, p := q.ans219, q.para219
fmt.Printf("【input】:%v 【output】:%v\n", p, containsNearbyDuplicate(p.one, p.k))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0834.Sum-of-Distances-in-Tree/834. Sum of Distances in Tree_test.go | leetcode/0834.Sum-of-Distances-in-Tree/834. Sum of Distances in Tree_test.go | package leetcode
import (
"fmt"
"testing"
)
type question834 struct {
para834
ans834
}
// para 是参数
// one 代表第一个参数
type para834 struct {
N int
edges [][]int
}
// ans 是答案
// one 代表第一个答案
type ans834 struct {
one []int
}
func Test_Problem834(t *testing.T) {
qs := []question834{
{
para834{4, [][]int{{1, 2}, {3, 2}, {3, 0}}},
ans834{[]int{6, 6, 4, 4}},
},
{
para834{6, [][]int{{0, 1}, {0, 2}, {2, 3}, {2, 4}, {2, 5}}},
ans834{[]int{8, 12, 6, 10, 10, 10}},
},
}
fmt.Printf("------------------------Leetcode Problem 834------------------------\n")
for _, q := range qs {
_, p := q.ans834, q.para834
fmt.Printf("【input】:%v 【output】:%v\n", p, sumOfDistancesInTree(p.N, p.edges))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0834.Sum-of-Distances-in-Tree/834. Sum of Distances in Tree.go | leetcode/0834.Sum-of-Distances-in-Tree/834. Sum of Distances in Tree.go | package leetcode
func sumOfDistancesInTree(N int, edges [][]int) []int {
// count[i] 中存储的是以 i 为根节点,所有子树结点和根节点的总数
tree, visited, count, res := make([][]int, N), make([]bool, N), make([]int, N), make([]int, N)
for _, e := range edges {
i, j := e[0], e[1]
tree[i] = append(tree[i], j)
tree[j] = append(tree[j], i)
}
deepFirstSearch(0, visited, count, res, tree)
// 重置访问状态,再进行一次 DFS
visited = make([]bool, N)
// 进入第二次 DFS 之前,只有 res[0] 里面存的是正确的值,因为第一次 DFS 计算出了以 0 为根节点的所有路径和
// 第二次 DFS 的目的是把以 0 为根节点的路径和转换成以 n 为根节点的路径和
deepSecondSearch(0, visited, count, res, tree)
return res
}
func deepFirstSearch(root int, visited []bool, count, res []int, tree [][]int) {
visited[root] = true
for _, n := range tree[root] {
if visited[n] {
continue
}
deepFirstSearch(n, visited, count, res, tree)
count[root] += count[n]
// root 节点到 n 的所有路径和 = 以 n 为根节点到所有子树的路径和 res[n] + root 到 count[n] 中每个节点的个数(root 节点和以 n 为根节点的每个节点都增加一条路径)
// root 节点和以 n 为根节点的每个节点都增加一条路径 = 以 n 为根节点,子树节点数和根节点数的总和,即 count[n]
res[root] += res[n] + count[n]
}
count[root]++
}
// 从 root 开始,把 root 节点的子节点,依次设置成新的根节点
func deepSecondSearch(root int, visited []bool, count, res []int, tree [][]int) {
N := len(visited)
visited[root] = true
for _, n := range tree[root] {
if visited[n] {
continue
}
// 根节点从 root 变成 n 后
// res[root] 存储的是以 root 为根节点到所有节点的路径总长度
// 1. root 到 n 节点增加的路径长度 = root 节点和以 n 为根节点的每个节点都增加一条路径 = 以 n 为根节点,子树节点数和根节点数的总和,即 count[n]
// 2. n 到以 n 为根节点的所有子树节点以外的节点增加的路径长度 = n 节点和非 n 为根节点子树的每个节点都增加一条路径 = N - count[n]
// 所以把根节点从 root 转移到 n,需要增加的路径是上面👆第二步计算的,需要减少的路径是上面👆第一步计算的
res[n] = res[root] + (N - count[n]) - count[n]
deepSecondSearch(n, visited, count, res, tree)
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0224.Basic-Calculator/224. Basic Calculator.go | leetcode/0224.Basic-Calculator/224. Basic Calculator.go | package leetcode
import (
"container/list"
"fmt"
"strconv"
)
// 解法一
func calculate(s string) int {
i, stack, result, sign := 0, list.New(), 0, 1 // 记录加减状态
for i < len(s) {
if s[i] == ' ' {
i++
} else if s[i] <= '9' && s[i] >= '0' { // 获取一段数字
base, v := 10, int(s[i]-'0')
for i+1 < len(s) && s[i+1] <= '9' && s[i+1] >= '0' {
v = v*base + int(s[i+1]-'0')
i++
}
result += v * sign
i++
} else if s[i] == '+' {
sign = 1
i++
} else if s[i] == '-' {
sign = -1
i++
} else if s[i] == '(' { // 把之前计算结果及加减状态压栈,开始新的计算
stack.PushBack(result)
stack.PushBack(sign)
result = 0
sign = 1
i++
} else if s[i] == ')' { // 新的计算结果 * 前一个加减状态 + 之前计算结果
result = result*stack.Remove(stack.Back()).(int) + stack.Remove(stack.Back()).(int)
i++
}
}
return result
}
// 解法二
func calculate1(s string) int {
stack := []byte{}
for i := 0; i < len(s); i++ {
if s[i] == ' ' {
continue
} else if s[i] == ')' {
tmp, index := "", len(stack)-1
for ; index >= 0; index-- {
if stack[index] == '(' {
break
}
}
tmp = string(stack[index+1:])
stack = stack[:index]
res := strconv.Itoa(calculateStr(tmp))
for j := 0; j < len(res); j++ {
stack = append(stack, res[j])
}
} else {
stack = append(stack, s[i])
}
}
fmt.Printf("stack = %v\n", string(stack))
return calculateStr(string(stack))
}
func calculateStr(str string) int {
s, nums, tmpStr, res := []byte{}, []int{}, "", 0
// 处理符号的问题,++得+,--得+,+-、-+得-
for i := 0; i < len(str); i++ {
if len(s) > 0 && s[len(s)-1] == '+' && str[i] == '+' {
continue
} else if len(s) > 0 && s[len(s)-1] == '+' && str[i] == '-' {
s[len(s)-1] = '-'
} else if len(s) > 0 && s[len(s)-1] == '-' && str[i] == '+' {
continue
} else if len(s) > 0 && s[len(s)-1] == '-' && str[i] == '-' {
s[len(s)-1] = '+'
} else {
s = append(s, str[i])
}
}
str = string(s)
s = []byte{}
for i := 0; i < len(str); i++ {
if isDigital(str[i]) {
tmpStr += string(str[i])
} else {
num, _ := strconv.Atoi(tmpStr)
nums = append(nums, num)
tmpStr = ""
s = append(s, str[i])
}
}
if tmpStr != "" {
num, _ := strconv.Atoi(tmpStr)
nums = append(nums, num)
}
res = nums[0]
for i := 0; i < len(s); i++ {
if s[i] == '+' {
res += nums[i+1]
} else {
res -= nums[i+1]
}
}
fmt.Printf("s = %v nums = %v res = %v\n", string(s), nums, res)
return res
}
func isDigital(v byte) bool {
if v >= '0' && v <= '9' {
return true
}
return false
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0224.Basic-Calculator/224. Basic Calculator_test.go | leetcode/0224.Basic-Calculator/224. Basic Calculator_test.go | package leetcode
import (
"fmt"
"testing"
)
type question224 struct {
para224
ans224
}
// para 是参数
// one 代表第一个参数
type para224 struct {
one string
}
// ans 是答案
// one 代表第一个答案
type ans224 struct {
one int
}
func Test_Problem224(t *testing.T) {
qs := []question224{
{
para224{"1 + 1"},
ans224{2},
},
{
para224{" 2-1 + 2 "},
ans224{3},
},
{
para224{"(1+(4+5+2)-3)+(6+8)"},
ans224{23},
},
{
para224{"2-(5-6)"},
ans224{3},
},
}
fmt.Printf("------------------------Leetcode Problem 224------------------------\n")
for _, q := range qs {
_, p := q.ans224, q.para224
fmt.Printf("【input】:%v 【output】:%v\n", p, calculate(p.one))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0784.Letter-Case-Permutation/784. Letter Case Permutation_test.go | leetcode/0784.Letter-Case-Permutation/784. Letter Case Permutation_test.go | package leetcode
import (
"fmt"
"testing"
)
type question784 struct {
para784
ans784
}
// para 是参数
// one 代表第一个参数
type para784 struct {
one string
}
// ans 是答案
// one 代表第一个答案
type ans784 struct {
one []string
}
func Test_Problem784(t *testing.T) {
qs := []question784{
{
para784{"mQe"},
ans784{[]string{"mqe", "mqE", "mQe", "mQE", "Mqe", "MqE", "MQe", "MQE"}},
},
{
para784{"C"},
ans784{[]string{"c", "C"}},
},
{
para784{"a1b2"},
ans784{[]string{"a1b2", "a1B2", "A1b2", "A1B2"}},
},
{
para784{"3z4"},
ans784{[]string{"3z4", "3Z4"}},
},
{
para784{"12345"},
ans784{[]string{"12345"}},
},
}
fmt.Printf("------------------------Leetcode Problem 784------------------------\n")
for _, q := range qs {
_, p := q.ans784, q.para784
fmt.Printf("【input】:%v 【output】:%v\n", p, letterCasePermutation1(p.one))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0784.Letter-Case-Permutation/784. Letter Case Permutation.go | leetcode/0784.Letter-Case-Permutation/784. Letter Case Permutation.go | package leetcode
import (
"strings"
)
// 解法一,DFS 深搜
func letterCasePermutation(S string) []string {
if len(S) == 0 {
return []string{}
}
res, pos, c := []string{}, []int{}, []int{}
SS := strings.ToLower(S)
for i := 0; i < len(SS); i++ {
if isLowerLetter(SS[i]) {
pos = append(pos, i)
}
}
for i := 0; i <= len(pos); i++ {
findLetterCasePermutation(SS, pos, i, 0, c, &res)
}
return res
}
func isLowerLetter(v byte) bool {
if v >= 'a' && v <= 'z' {
return true
}
return false
}
func findLetterCasePermutation(s string, pos []int, target, index int, c []int, res *[]string) {
if len(c) == target {
b := []byte(s)
for _, v := range c {
b[pos[v]] -= 'a' - 'A'
}
*res = append(*res, string(b))
return
}
for i := index; i < len(pos)-(target-len(c))+1; i++ {
c = append(c, i)
findLetterCasePermutation(s, pos, target, i+1, c, res)
c = c[:len(c)-1]
}
}
// 解法二,先讲第一个字母变大写,然后依次把后面的字母变大写。最终的解数组中答案是翻倍增长的
// 第一步:
// [mqe] -> [mqe, Mqe]
// 第二步:
// [mqe, Mqe] -> [mqe Mqe mQe MQe]
// 第二步:
// [mqe Mqe mQe MQe] -> [mqe Mqe mQe MQe mqE MqE mQE MQE]
func letterCasePermutation1(S string) []string {
res := make([]string, 0, 1<<uint(len(S)))
S = strings.ToLower(S)
for k, v := range S {
if isLetter784(byte(v)) {
switch len(res) {
case 0:
res = append(res, S, toUpper(S, k))
default:
for _, s := range res {
res = append(res, toUpper(s, k))
}
}
}
}
if len(res) == 0 {
res = append(res, S)
}
return res
}
func isLetter784(c byte) bool {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
}
func toUpper(s string, i int) string {
b := []byte(s)
b[i] -= 'a' - 'A'
return string(b)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0863.All-Nodes-Distance-K-in-Binary-Tree/863. All Nodes Distance K in Binary Tree_test.go | leetcode/0863.All-Nodes-Distance-K-in-Binary-Tree/863. All Nodes Distance K in Binary Tree_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question863 struct {
para863
ans863
}
// para 是参数
// one 代表第一个参数
type para863 struct {
root []int
target []int
K int
}
// ans 是答案
// one 代表第一个答案
type ans863 struct {
one []int
}
func Test_Problem863(t *testing.T) {
qs := []question863{
{
para863{[]int{3, 5, 1, 6, 2, 0, 8, structures.NULL, structures.NULL, 7, 4}, []int{5}, 2},
ans863{[]int{7, 4, 1}},
},
}
fmt.Printf("------------------------Leetcode Problem 863------------------------\n")
for _, q := range qs {
_, p := q.ans863, q.para863
tree, target := structures.Ints2TreeNode(p.root), structures.Ints2TreeNode(p.target)
fmt.Printf("【input】:%v 【output】:%v\n", p, distanceK(tree, target, p.K))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0863.All-Nodes-Distance-K-in-Binary-Tree/863. All Nodes Distance K in Binary Tree.go | leetcode/0863.All-Nodes-Distance-K-in-Binary-Tree/863. All Nodes Distance K in Binary Tree.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func distanceK(root *TreeNode, target *TreeNode, K int) []int {
visit := []int{}
findDistanceK(root, target, K, &visit)
return visit
}
func findDistanceK(root, target *TreeNode, K int, visit *[]int) int {
if root == nil {
return -1
}
if root == target {
findChild(root, K, visit)
return K - 1
}
leftDistance := findDistanceK(root.Left, target, K, visit)
if leftDistance == 0 {
findChild(root, leftDistance, visit)
}
if leftDistance > 0 {
findChild(root.Right, leftDistance-1, visit)
return leftDistance - 1
}
rightDistance := findDistanceK(root.Right, target, K, visit)
if rightDistance == 0 {
findChild(root, rightDistance, visit)
}
if rightDistance > 0 {
findChild(root.Left, rightDistance-1, visit)
return rightDistance - 1
}
return -1
}
func findChild(root *TreeNode, K int, visit *[]int) {
if root == nil {
return
}
if K == 0 {
*visit = append(*visit, root.Val)
} else {
findChild(root.Left, K-1, visit)
findChild(root.Right, K-1, visit)
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/2167. Minimum Time to Remove All Cars Containing Illegal Goods_test.go | leetcode/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/2167. Minimum Time to Remove All Cars Containing Illegal Goods_test.go | package leetcode
import (
"fmt"
"testing"
)
type question2167 struct {
para2167
ans2167
}
// para 是参数
// one 代表第一个参数
type para2167 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans2167 struct {
one int
}
func Test_Problem2167(t *testing.T) {
qs := []question2167{
{
para2167{"1100101"},
ans2167{5},
},
{
para2167{"0010"},
ans2167{2},
},
{
para2167{"1100111101"},
ans2167{8},
},
{
para2167{"1001010101"},
ans2167{8},
},
}
fmt.Printf("------------------------Leetcode Problem 2167------------------------\n")
for _, q := range qs {
_, p := q.ans2167, q.para2167
fmt.Printf("【input】:%v 【output】:%v\n", p, minimumTime(p.s))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/2167. Minimum Time to Remove All Cars Containing Illegal Goods.go | leetcode/2167.Minimum-Time-to-Remove-All-Cars-Containing-Illegal-Goods/2167. Minimum Time to Remove All Cars Containing Illegal Goods.go | package leetcode
import "runtime/debug"
// 解法一 DP
func minimumTime(s string) int {
suffixSum, prefixSum, res := make([]int, len(s)+1), make([]int, len(s)+1), 0
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '0' {
suffixSum[i] = suffixSum[i+1]
} else {
suffixSum[i] = min(suffixSum[i+1]+2, len(s)-i)
}
}
res = suffixSum[0]
if s[0] == '1' {
prefixSum[0] = 1
}
for i := 1; i < len(s); i++ {
if s[i] == '0' {
prefixSum[i] = prefixSum[i-1]
} else {
prefixSum[i] = min(prefixSum[i-1]+2, i+1)
}
res = min(res, prefixSum[i]+suffixSum[i+1])
}
return res
}
func init() { debug.SetGCPercent(-1) }
// 解法二 小幅优化时间和空间复杂度
func minimumTime1(s string) int {
res, count := len(s), 0
for i := 0; i < len(s); i++ {
count = min(count+int(s[i]-'0')*2, i+1)
res = min(res, count+len(s)-i-1)
}
return res
}
func min(a, b int) int {
if a < b {
return a
} else {
return b
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1652.Defuse-the-Bomb/1652. Defuse the Bomb.go | leetcode/1652.Defuse-the-Bomb/1652. Defuse the Bomb.go | package leetcode
func decrypt(code []int, k int) []int {
if k == 0 {
for i := 0; i < len(code); i++ {
code[i] = 0
}
return code
}
count, sum, res := k, 0, make([]int, len(code))
if k > 0 {
for i := 0; i < len(code); i++ {
for j := i + 1; j < len(code); j++ {
if count == 0 {
break
}
sum += code[j]
count--
}
if count > 0 {
for j := 0; j < len(code); j++ {
if count == 0 {
break
}
sum += code[j]
count--
}
}
res[i] = sum
sum, count = 0, k
}
}
if k < 0 {
for i := 0; i < len(code); i++ {
for j := i - 1; j >= 0; j-- {
if count == 0 {
break
}
sum += code[j]
count++
}
if count < 0 {
for j := len(code) - 1; j >= 0; j-- {
if count == 0 {
break
}
sum += code[j]
count++
}
}
res[i] = sum
sum, count = 0, k
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1652.Defuse-the-Bomb/1652. Defuse the Bomb_test.go | leetcode/1652.Defuse-the-Bomb/1652. Defuse the Bomb_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1652 struct {
para1652
ans1652
}
// para 是参数
// one 代表第一个参数
type para1652 struct {
code []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans1652 struct {
one []int
}
func Test_Problem1652(t *testing.T) {
qs := []question1652{
{
para1652{[]int{5, 7, 1, 4}, 3},
ans1652{[]int{12, 10, 16, 13}},
},
{
para1652{[]int{1, 2, 3, 4}, 0},
ans1652{[]int{0, 0, 0, 0}},
},
{
para1652{[]int{2, 4, 9, 3}, -2},
ans1652{[]int{12, 5, 6, 13}},
},
}
fmt.Printf("------------------------Leetcode Problem 1652------------------------\n")
for _, q := range qs {
_, p := q.ans1652, q.para1652
fmt.Printf("【input】:%v 【output】:%v \n", p, decrypt(p.code, p.k))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1171.Remove-Zero-Sum-Consecutive-Nodes-from-Linked-List/1171. Remove Zero Sum Consecutive Nodes from Linked List.go | leetcode/1171.Remove-Zero-Sum-Consecutive-Nodes-from-Linked-List/1171. Remove Zero Sum Consecutive Nodes from Linked List.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// ListNode define
type ListNode = structures.ListNode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
// 解法一
func removeZeroSumSublists(head *ListNode) *ListNode {
// 计算累加和,和作为 key 存在 map 中,value 存那个节点的指针。如果字典中出现了重复的和,代表出现了和为 0 的段。
sum, sumMap, cur := 0, make(map[int]*ListNode), head
// 字典中增加 0 这个特殊值,是为了防止最终链表全部消除完
sumMap[0] = nil
for cur != nil {
sum = sum + cur.Val
if ptr, ok := sumMap[sum]; ok {
// 在字典中找到了重复的和,代表 [ptr, tmp] 中间的是和为 0 的段,要删除的就是这一段。
// 同时删除 map 中中间这一段的和
if ptr != nil {
iter := ptr.Next
tmpSum := sum + iter.Val
for tmpSum != sum {
// 删除中间为 0 的那一段,tmpSum 不断的累加删除 map 中的和
delete(sumMap, tmpSum)
iter = iter.Next
tmpSum = tmpSum + iter.Val
}
ptr.Next = cur.Next
} else {
head = cur.Next
sumMap = make(map[int]*ListNode)
sumMap[0] = nil
}
} else {
sumMap[sum] = cur
}
cur = cur.Next
}
return head
}
// 解法二 暴力解法
func removeZeroSumSublists1(head *ListNode) *ListNode {
if head == nil {
return nil
}
h, prefixSumMap, sum, counter, lastNode := head, map[int]int{}, 0, 0, &ListNode{Val: 1010}
for h != nil {
for h != nil {
sum += h.Val
counter++
if v, ok := prefixSumMap[sum]; ok {
lastNode, counter = h, v
break
}
if sum == 0 {
head = h.Next
break
}
prefixSumMap[sum] = counter
h = h.Next
}
if lastNode.Val != 1010 {
h = head
for counter > 1 {
counter--
h = h.Next
}
h.Next = lastNode.Next
}
if h == nil {
break
} else {
h, prefixSumMap, sum, counter, lastNode = head, map[int]int{}, 0, 0, &ListNode{Val: 1010}
}
}
return head
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1171.Remove-Zero-Sum-Consecutive-Nodes-from-Linked-List/1171. Remove Zero Sum Consecutive Nodes from Linked List_test.go | leetcode/1171.Remove-Zero-Sum-Consecutive-Nodes-from-Linked-List/1171. Remove Zero Sum Consecutive Nodes from Linked List_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question1171 struct {
para1171
ans1171
}
// para 是参数
// one 代表第一个参数
type para1171 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans1171 struct {
one []int
}
func Test_Problem1171(t *testing.T) {
qs := []question1171{
{
para1171{[]int{1, 2, -3, 3, 1}},
ans1171{[]int{3, 1}},
},
{
para1171{[]int{1, 2, 3, -3, 4}},
ans1171{[]int{1, 2, 4}},
},
{
para1171{[]int{1, 2, 3, -3, -2}},
ans1171{[]int{1}},
},
{
para1171{[]int{1, -1}},
ans1171{[]int{}},
},
}
fmt.Printf("------------------------Leetcode Problem 1171------------------------\n")
for _, q := range qs {
_, p := q.ans1171, q.para1171
fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(removeZeroSumSublists(structures.Ints2List(p.one))))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.