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/0693.Binary-Number-with-Alternating-Bits/693. Binary Number with Alternating Bits_test.go | leetcode/0693.Binary-Number-with-Alternating-Bits/693. Binary Number with Alternating Bits_test.go | package leetcode
import (
"fmt"
"testing"
)
type question693 struct {
para693
ans693
}
// para 是参数
// one 代表第一个参数
type para693 struct {
one int
}
// ans 是答案
// one 代表第一个答案
type ans693 struct {
one bool
}
func Test_Problem693(t *testing.T) {
qs := []question693{
{
para693{5},
ans693{true},
},
{
para693{7},
ans693{false},
},
{
para693{11},
ans693{false},
},
{
para693{10},
ans693{true},
},
}
fmt.Printf("------------------------Leetcode Problem 693------------------------\n")
for _, q := range qs {
_, p := q.ans693, q.para693
fmt.Printf("【input】:%v 【output】:%v\n", p, hasAlternatingBits(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/0693.Binary-Number-with-Alternating-Bits/693. Binary Number with Alternating Bits.go | leetcode/0693.Binary-Number-with-Alternating-Bits/693. Binary Number with Alternating Bits.go | package leetcode
// 解法一
func hasAlternatingBits(n int) bool {
/*
n = 1 0 1 0 1 0 1 0
n >> 1 0 1 0 1 0 1 0 1
n ^ n>>1 1 1 1 1 1 1 1 1
n 1 1 1 1 1 1 1 1
n + 1 1 0 0 0 0 0 0 0 0
n & (n+1) 0 0 0 0 0 0 0 0
*/
n = n ^ (n >> 1)
return (n & (n + 1)) == 0
}
// 解法二
func hasAlternatingBits1(n int) bool {
last, current := 0, 0
for n > 0 {
last = n & 1
n = n / 2
current = n & 1
if last == current {
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/0372.Super-Pow/372. Super Pow_test.go | leetcode/0372.Super-Pow/372. Super Pow_test.go | package leetcode
import (
"fmt"
"testing"
)
type question372 struct {
para372
ans372
}
// para 是参数
// one 代表第一个参数
type para372 struct {
a int
b []int
}
// ans 是答案
// one 代表第一个答案
type ans372 struct {
one int
}
func Test_Problem372(t *testing.T) {
qs := []question372{
{
para372{2, []int{3}},
ans372{8},
},
{
para372{2, []int{1, 0}},
ans372{1024},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 372------------------------\n")
for _, q := range qs {
_, p := q.ans372, q.para372
fmt.Printf("【input】:%v 【output】:%v\n", p, superPow(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/0372.Super-Pow/372. Super Pow.go | leetcode/0372.Super-Pow/372. Super Pow.go | package leetcode
// 解法一 快速幂 res = res^10 * qpow(a, b[i])
// 模运算性质一:(a + b) % p = (a % p + b % p) % p
// 模运算性质二:(a - b) % p = (a % p - b % p + p) % p
// 模运算性质三:(a * b) % p = (a % p * b % p) % p
// 模运算性质四:a ^ b % p = ((a % p)^b) % p
// 模运算性质五:ab % p = ((a % p) * ( b % p)) % p, 其中 ab 是一个数字,如:2874,98374 等等
// 举个例子
// 12345^678 % 1337 = (12345^670 * 12345^8) % 1337
//
// = ((12345^670 % 1337) * (12345^8 % 1337)) % 1337 ---> 利用性质 三
// = (((12345^67)^10 % 1337) * (12345^8 % 1337)) % 1337 ---> 乘方性质
// = ((12345^67 % 1337)^10) % 1337 * (12345^8 % 1337)) % 1337 ---> 利用性质 四
// = (((12345^67 % 1337)^10) * (12345^8 % 1337)) % 1337 ---> 反向利用性质 三
func superPow(a int, b []int) int {
res := 1
for i := 0; i < len(b); i++ {
res = (qpow(res, 10) * qpow(a, b[i])) % 1337
}
return res
}
// 快速幂计算 x^n
func qpow(x, n int) int {
res := 1
x %= 1337
for n > 0 {
if (n & 1) == 1 {
res = (res * x) % 1337
}
x = (x * x) % 1337
n >>= 1
}
return res
}
// 解法二 暴力解法
// 利用上面的性质,可以得到:a^1234567 % 1337 = (a^1234560 % 1337) * (a^7 % 1337) % k = ((((a^123456) % 1337)^10)% 1337 * (a^7 % 1337))% 1337;
func superPow1(a int, b []int) int {
if len(b) == 0 {
return 1
}
last := b[len(b)-1]
l := 1
// 先计算个位的 a^x 结果,对应上面例子中的 (a^7 % 1337)% 1337
for i := 1; i <= last; i++ {
l = l * a % 1337
}
// 再计算除去个位以外的 a^y 的结果,对应上面例子中的 (a^123456) % 1337)
temp := superPow1(a, b[:len(b)-1])
f := 1
// 对应上面例子中的 (((a^123456) % 1337)^10)% 1337
for i := 1; i <= 10; i++ {
f = f * temp % 1337
}
return f * l % 1337
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0096.Unique-Binary-Search-Trees/96. Unique Binary Search Trees.go | leetcode/0096.Unique-Binary-Search-Trees/96. Unique Binary Search Trees.go | package leetcode
func numTrees(n int) int {
dp := make([]int, n+1)
dp[0], dp[1] = 1, 1
for i := 2; i <= n; i++ {
for j := 1; j <= i; j++ {
dp[i] += dp[j-1] * dp[i-j]
}
}
return dp[n]
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0096.Unique-Binary-Search-Trees/96. Unique Binary Search Trees_test.go | leetcode/0096.Unique-Binary-Search-Trees/96. Unique Binary Search Trees_test.go | package leetcode
import (
"fmt"
"testing"
)
type question96 struct {
para96
ans96
}
// para 是参数
// one 代表第一个参数
type para96 struct {
one int
}
// ans 是答案
// one 代表第一个答案
type ans96 struct {
one int
}
func Test_Problem96(t *testing.T) {
qs := []question96{
{
para96{1},
ans96{1},
},
{
para96{3},
ans96{5},
},
{
para96{4},
ans96{14},
},
{
para96{5},
ans96{42},
},
{
para96{6},
ans96{132},
},
{
para96{7},
ans96{429},
},
{
para96{8},
ans96{1430},
},
{
para96{9},
ans96{4862},
},
{
para96{10},
ans96{16796},
},
}
fmt.Printf("------------------------Leetcode Problem 96------------------------\n")
for _, q := range qs {
_, p := q.ans96, q.para96
fmt.Printf("【input】:%v 【output】:%v\n", p, numTrees(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/0399.Evaluate-Division/399. Evaluate Division_test.go | leetcode/0399.Evaluate-Division/399. Evaluate Division_test.go | package leetcode
import (
"fmt"
"testing"
)
type question399 struct {
para399
ans399
}
// para 是参数
// one 代表第一个参数
type para399 struct {
e [][]string
v []float64
q [][]string
}
// ans 是答案
// one 代表第一个答案
type ans399 struct {
one []float64
}
func Test_Problem399(t *testing.T) {
qs := []question399{
{
para399{[][]string{{"a", "b"}, {"b", "c"}}, []float64{2.0, 3.0}, [][]string{{"a", "c"}, {"b", "a"}, {"a", "e"}, {"a", "a"}, {"x", "x"}}},
ans399{[]float64{6.0, 0.5, -1.0, 1.0, -1.0}},
},
}
fmt.Printf("------------------------Leetcode Problem 399------------------------\n")
for _, q := range qs {
_, p := q.ans399, q.para399
fmt.Printf("【input】:%v 【output】:%v\n", p, calcEquation(p.e, p.v, p.q))
}
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/0399.Evaluate-Division/399. Evaluate Division.go | leetcode/0399.Evaluate-Division/399. Evaluate Division.go | package leetcode
type stringUnionFind struct {
parents map[string]string
vals map[string]float64
}
func (suf stringUnionFind) add(x string) {
if _, ok := suf.parents[x]; ok {
return
}
suf.parents[x] = x
suf.vals[x] = 1.0
}
func (suf stringUnionFind) find(x string) string {
p := ""
if v, ok := suf.parents[x]; ok {
p = v
} else {
p = x
}
if x != p {
pp := suf.find(p)
suf.vals[x] *= suf.vals[p]
suf.parents[x] = pp
}
if v, ok := suf.parents[x]; ok {
return v
}
return x
}
func (suf stringUnionFind) union(x, y string, v float64) {
suf.add(x)
suf.add(y)
px, py := suf.find(x), suf.find(y)
suf.parents[px] = py
// x / px = vals[x]
// x / y = v
// 由上面 2 个式子就可以得出 px = v * vals[y] / vals[x]
suf.vals[px] = v * suf.vals[y] / suf.vals[x]
}
func calcEquation(equations [][]string, values []float64, queries [][]string) []float64 {
res, suf := make([]float64, len(queries)), stringUnionFind{parents: map[string]string{}, vals: map[string]float64{}}
for i := 0; i < len(values); i++ {
suf.union(equations[i][0], equations[i][1], values[i])
}
for i := 0; i < len(queries); i++ {
x, y := queries[i][0], queries[i][1]
if _, ok := suf.parents[x]; ok {
if _, ok := suf.parents[y]; ok {
if suf.find(x) == suf.find(y) {
res[i] = suf.vals[x] / suf.vals[y]
} else {
res[i] = -1
}
} else {
res[i] = -1
}
} else {
res[i] = -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/1003.Check-If-Word-Is-Valid-After-Substitutions/1003. Check If Word Is Valid After Substitutions_test.go | leetcode/1003.Check-If-Word-Is-Valid-After-Substitutions/1003. Check If Word Is Valid After Substitutions_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1003 struct {
para1003
ans1003
}
// para 是参数
// one 代表第一个参数
type para1003 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans1003 struct {
one bool
}
func Test_Problem1003(t *testing.T) {
qs := []question1003{
{
para1003{"aabcbc"},
ans1003{true},
},
{
para1003{"abcabcababcc"},
ans1003{true},
},
{
para1003{"abccba"},
ans1003{false},
},
{
para1003{"cababc"},
ans1003{false},
},
}
fmt.Printf("------------------------Leetcode Problem 1003------------------------\n")
for _, q := range qs {
_, p := q.ans1003, q.para1003
fmt.Printf("【input】:%v 【output】:%v\n", p, isValid1003(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/1003.Check-If-Word-Is-Valid-After-Substitutions/1003. Check If Word Is Valid After Substitutions.go | leetcode/1003.Check-If-Word-Is-Valid-After-Substitutions/1003. Check If Word Is Valid After Substitutions.go | package leetcode
func isValid1003(S string) bool {
if len(S) < 3 {
return false
}
stack := []byte{}
for i := 0; i < len(S); i++ {
if S[i] == 'a' {
stack = append(stack, S[i])
} else if S[i] == 'b' {
if len(stack) > 0 && stack[len(stack)-1] == 'a' {
stack = append(stack, S[i])
} else {
return false
}
} else {
if len(stack) > 1 && stack[len(stack)-1] == 'b' && stack[len(stack)-2] == 'a' {
stack = stack[:len(stack)-2]
} else {
return false
}
}
}
return len(stack) == 0
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0821.Shortest-Distance-to-a-Character/821. Shortest Distance to a Character_test.go | leetcode/0821.Shortest-Distance-to-a-Character/821. Shortest Distance to a Character_test.go | package leetcode
import (
"fmt"
"testing"
)
type question821 struct {
para821
ans821
}
// para 是参数
// one 代表第一个参数
type para821 struct {
s string
c byte
}
// ans 是答案
// one 代表第一个答案
type ans821 struct {
one []int
}
func Test_Problem821(t *testing.T) {
qs := []question821{
{
para821{"loveleetcode", 'e'},
ans821{[]int{3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0}},
},
{
para821{"baaa", 'b'},
ans821{[]int{0, 1, 2, 3}},
},
}
fmt.Printf("------------------------Leetcode Problem 821------------------------\n")
for _, q := range qs {
_, p := q.ans821, q.para821
fmt.Printf("【input】:%v 【output】:%v\n", p, shortestToChar(p.s, p.c))
}
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/0821.Shortest-Distance-to-a-Character/821. Shortest Distance to a Character.go | leetcode/0821.Shortest-Distance-to-a-Character/821. Shortest Distance to a Character.go | package leetcode
import (
"math"
)
// 解法一
func shortestToChar(s string, c byte) []int {
n := len(s)
res := make([]int, n)
for i := range res {
res[i] = n
}
for i := 0; i < n; i++ {
if s[i] == c {
res[i] = 0
} else if i > 0 {
res[i] = res[i-1] + 1
}
}
for i := n - 1; i >= 0; i-- {
if i < n-1 && res[i+1]+1 < res[i] {
res[i] = res[i+1] + 1
}
}
return res
}
// 解法二
func shortestToChar1(s string, c byte) []int {
res := make([]int, len(s))
for i := 0; i < len(s); i++ {
if s[i] == c {
res[i] = 0
} else {
left, right := math.MaxInt32, math.MaxInt32
for j := i + 1; j < len(s); j++ {
if s[j] == c {
right = j - i
break
}
}
for k := i - 1; k >= 0; k-- {
if s[k] == c {
left = i - k
break
}
}
res[i] = min(left, right)
}
}
return res
}
func min(a, 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/0958.Check-Completeness-of-a-Binary-Tree/0958.Check Completeness of a Binary Tree.go | leetcode/0958.Check-Completeness-of-a-Binary-Tree/0958.Check Completeness of a 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 isCompleteTree(root *TreeNode) bool {
queue, found := []*TreeNode{root}, false
for len(queue) > 0 {
node := queue[0] //取出每一层的第一个节点
queue = queue[1:]
if node == nil {
found = true
} else {
if found {
return false // 层序遍历中,两个不为空的节点中出现一个 nil
}
//如果左孩子为nil,则append进去的node.Left为nil
queue = append(queue, node.Left, node.Right)
}
}
return true
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0958.Check-Completeness-of-a-Binary-Tree/0958.Check Completeness of a Binary Tree_test.go | leetcode/0958.Check-Completeness-of-a-Binary-Tree/0958.Check Completeness of a Binary Tree_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question958 struct {
para958
ans958
}
// para 是参数
// one 代表第一个参数
type para958 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans958 struct {
one bool
}
func Test_Problem958(t *testing.T) {
qs := []question958{
{
para958{[]int{1, 2, 3, 4, 5, 6}},
ans958{true},
},
{
para958{[]int{1, 2, 3, 4, 5, structures.NULL, 7}},
ans958{false},
},
}
fmt.Printf("------------------------Leetcode Problem 958------------------------\n")
for _, q := range qs {
_, p := q.ans958, q.para958
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", isCompleteTree(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/0260.Single-Number-III/260. Single Number III.go | leetcode/0260.Single-Number-III/260. Single Number III.go | package leetcode
func singleNumberIII(nums []int) []int {
diff := 0
for _, num := range nums {
diff ^= num
}
// Get its last set bit (lsb)
diff &= -diff
res := []int{0, 0} // this array stores the two numbers we will return
for _, num := range nums {
if (num & diff) == 0 { // the bit is not set
res[0] ^= num
} else { // the bit is set
res[1] ^= num
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0260.Single-Number-III/260. Single Number III_test.go | leetcode/0260.Single-Number-III/260. Single Number III_test.go | package leetcode
import (
"fmt"
"testing"
)
type question260 struct {
para260
ans260
}
// para 是参数
// one 代表第一个参数
type para260 struct {
s []int
}
// ans 是答案
// one 代表第一个答案
type ans260 struct {
one []int
}
func Test_Problem260(t *testing.T) {
qs := []question260{
{
para260{[]int{1, 2, 1, 3, 2, 5}},
ans260{[]int{3, 5}},
},
}
fmt.Printf("------------------------Leetcode Problem 260------------------------\n")
for _, q := range qs {
_, p := q.ans260, q.para260
fmt.Printf("【input】:%v 【output】:%v\n", p, singleNumberIII(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/0116.Populating-Next-Right-Pointers-in-Each-Node/116.Populating Next Right Pointers in Each Node.go | leetcode/0116.Populating-Next-Right-Pointers-in-Each-Node/116.Populating Next Right Pointers in Each Node.go | package leetcode
type Node struct {
Val int
Left *Node
Right *Node
Next *Node
}
// 解法一:迭代
func connect(root *Node) *Node {
if root == nil {
return root
}
q := []*Node{root}
for len(q) > 0 {
var p []*Node
// 遍历这一层的所有节点
for i, node := range q {
if i+1 < len(q) {
node.Next = q[i+1]
}
if node.Left != nil {
p = append(p, node.Left)
}
if node.Right != nil {
p = append(p, node.Right)
}
}
q = p
}
return root
}
// 解法二 递归
func connect2(root *Node) *Node {
if root == nil {
return nil
}
connectTwoNode(root.Left, root.Right)
return root
}
func connectTwoNode(node1, node2 *Node) {
if node1 == nil || node2 == nil {
return
}
node1.Next = node2
connectTwoNode(node1.Left, node1.Right)
connectTwoNode(node2.Left, node2.Right)
connectTwoNode(node1.Right, node2.Left)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0116.Populating-Next-Right-Pointers-in-Each-Node/116.Populating Next Right Pointers in Each Node_test.go | leetcode/0116.Populating-Next-Right-Pointers-in-Each-Node/116.Populating Next Right Pointers in Each Node_test.go | package leetcode
import (
"fmt"
"testing"
)
type question116 struct {
para116
ans116
}
// para 是参数
// one 代表第一个参数
type para116 struct {
one *Node
}
// ans 是答案
// one 代表第一个答案
type ans116 struct {
one *Node
}
func newQuestionNode() *Node {
node7 := &Node{}
node7.Val = 7
node6 := &Node{}
node6.Val = 6
node5 := &Node{}
node5.Val = 5
node4 := &Node{}
node4.Val = 4
node3 := &Node{}
node3.Val = 3
node2 := &Node{}
node2.Val = 2
node1 := &Node{}
node1.Val = 1
node1.Left = node2
node1.Right = node3
node2.Left = node4
node2.Right = node5
node3.Left = node6
node3.Right = node7
return node1
}
func newResultNode() *Node {
node7 := &Node{}
node7.Val = 7
node6 := &Node{}
node6.Val = 6
node5 := &Node{}
node5.Val = 5
node4 := &Node{}
node4.Val = 4
node3 := &Node{}
node3.Val = 3
node2 := &Node{}
node2.Val = 2
node1 := &Node{}
node1.Val = 1
node1.Left = node2
node1.Right = node3
node2.Left = node4
node2.Right = node5
node3.Left = node6
node3.Right = node7
node1.Next = nil
node2.Next = node3
node3.Next = nil
node4.Next = node5
node5.Next = node6
node6.Next = node7
node7.Next = nil
return node1
}
func Test_Problem116(t *testing.T) {
qs := []question116{
{
para116{newQuestionNode()},
ans116{newResultNode()},
},
}
fmt.Printf("------------------------Leetcode Problem 116------------------------\n")
for _, q := range qs {
_, p := q.ans116, q.para116
fmt.Printf("【input】:%v ", p.one)
fmt.Printf("【output】:%v \n", connect(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/0162.Find-Peak-Element/162. Find Peak Element.go | leetcode/0162.Find-Peak-Element/162. Find Peak Element.go | package leetcode
// 解法一 二分
func findPeakElement(nums []int) int {
if len(nums) == 0 || len(nums) == 1 {
return 0
}
low, high := 0, len(nums)-1
for low <= high {
mid := low + (high-low)>>1
if (mid == len(nums)-1 && nums[mid-1] < nums[mid]) || (mid > 0 && nums[mid-1] < nums[mid] && (mid <= len(nums)-2 && nums[mid+1] < nums[mid])) || (mid == 0 && nums[1] < nums[0]) {
return mid
}
if mid > 0 && nums[mid-1] < nums[mid] {
low = mid + 1
}
if mid > 0 && nums[mid-1] > nums[mid] {
high = mid - 1
}
if mid == low {
low++
}
if mid == high {
high--
}
}
return -1
}
// 解法二 二分
func findPeakElement1(nums []int) int {
low, high := 0, len(nums)-1
for low < high {
mid := low + (high-low)>>1
// 如果 mid 较大,则左侧存在峰值,high = m,如果 mid + 1 较大,则右侧存在峰值,low = mid + 1
if nums[mid] > nums[mid+1] {
high = mid
} else {
low = mid + 1
}
}
return low
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0162.Find-Peak-Element/162. Find Peak Element_test.go | leetcode/0162.Find-Peak-Element/162. Find Peak Element_test.go | package leetcode
import (
"fmt"
"testing"
)
type question162 struct {
para162
ans162
}
// para 是参数
// one 代表第一个参数
type para162 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans162 struct {
one int
}
func Test_Problem162(t *testing.T) {
qs := []question162{
{
para162{[]int{2, 1, 2}},
ans162{0},
},
{
para162{[]int{3, 2, 1}},
ans162{0},
},
{
para162{[]int{1, 2}},
ans162{1},
},
{
para162{[]int{2, 1}},
ans162{0},
},
{
para162{[]int{1}},
ans162{0},
},
{
para162{[]int{1, 2, 3, 1}},
ans162{2},
},
{
para162{[]int{1, 2, 1, 3, 5, 6, 4}},
ans162{5},
},
}
fmt.Printf("------------------------Leetcode Problem 162------------------------\n")
for _, q := range qs {
_, p := q.ans162, q.para162
fmt.Printf("【input】:%v 【output】:%v\n", p, findPeakElement(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/0922.Sort-Array-By-Parity-II/922. Sort Array By Parity II.go | leetcode/0922.Sort-Array-By-Parity-II/922. Sort Array By Parity II.go | package leetcode
func sortArrayByParityII(A []int) []int {
if len(A) == 0 || len(A)%2 != 0 {
return []int{}
}
res := make([]int, len(A))
oddIndex := 1
evenIndex := 0
for i := 0; i < len(A); i++ {
if A[i]%2 == 0 {
res[evenIndex] = A[i]
evenIndex += 2
} else {
res[oddIndex] = A[i]
oddIndex += 2
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0922.Sort-Array-By-Parity-II/922. Sort Array By Parity II_test.go | leetcode/0922.Sort-Array-By-Parity-II/922. Sort Array By Parity II_test.go | package leetcode
import (
"fmt"
"testing"
)
type question922 struct {
para922
ans922
}
// para 是参数
// one 代表第一个参数
type para922 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans922 struct {
one []int
}
func Test_Problem922(t *testing.T) {
qs := []question922{
{
para922{[]int{}},
ans922{[]int{}},
},
{
para922{[]int{1}},
ans922{[]int{}},
},
{
para922{[]int{4, 2, 5, 7}},
ans922{[]int{4, 5, 2, 7}},
},
}
fmt.Printf("------------------------Leetcode Problem 922------------------------\n")
for _, q := range qs {
_, p := q.ans922, q.para922
fmt.Printf("【input】:%v 【output】:%v\n", p, sortArrayByParityII(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/1290.Convert-Binary-Number-in-a-Linked-List-to-Integer/1290. Convert Binary Number in a Linked List to Integer_test.go | leetcode/1290.Convert-Binary-Number-in-a-Linked-List-to-Integer/1290. Convert Binary Number in a Linked List to Integer_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question1290 struct {
para1290
ans1290
}
// para 是参数
// one 代表第一个参数
type para1290 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans1290 struct {
one int
}
func Test_Problem1290(t *testing.T) {
qs := []question1290{
{
para1290{[]int{1, 0, 1}},
ans1290{5},
},
{
para1290{[]int{0}},
ans1290{0},
},
{
para1290{[]int{1}},
ans1290{1},
},
{
para1290{[]int{0, 0}},
ans1290{0},
},
{
para1290{[]int{1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0}},
ans1290{18880},
},
}
fmt.Printf("------------------------Leetcode Problem 1290------------------------\n")
for _, q := range qs {
_, p := q.ans1290, q.para1290
fmt.Printf("【input】:%v 【output】:%v\n", p, getDecimalValue(structures.Ints2List(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/1290.Convert-Binary-Number-in-a-Linked-List-to-Integer/1290. Convert Binary Number in a Linked List to Integer.go | leetcode/1290.Convert-Binary-Number-in-a-Linked-List-to-Integer/1290. Convert Binary Number in a Linked List to Integer.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 getDecimalValue(head *ListNode) int {
sum := 0
for head != nil {
sum = sum*2 + head.Val
head = head.Next
}
return sum
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1663.Smallest-String-With-A-Given-Numeric-Value/1663. Smallest String With A Given Numeric Value.go | leetcode/1663.Smallest-String-With-A-Given-Numeric-Value/1663. Smallest String With A Given Numeric Value.go | package leetcode
// 解法一 贪心
func getSmallestString(n int, k int) string {
str, i, j := make([]byte, n), 0, 0
for i = n - 1; i <= k-26; i, k = i-1, k-26 {
str[i] = 'z'
}
if i >= 0 {
str[i] = byte('a' + k - 1 - i)
for ; j < i; j++ {
str[j] = 'a'
}
}
return string(str)
}
// 解法二 DFS
func getSmallestString1(n int, k int) string {
if n == 0 {
return ""
}
res, c := "", []byte{}
findSmallestString(0, n, k, 0, c, &res)
return res
}
func findSmallestString(value int, length, k, index int, str []byte, res *string) {
if len(str) == length && value == k {
tmp := string(str)
if (*res) == "" {
*res = tmp
}
if tmp < *res && *res != "" {
*res = tmp
}
return
}
if len(str) >= index && (*res) != "" && str[index-1] > (*res)[index-1] {
return
}
for j := 0; j < 26; j++ {
if k-value > (length-len(str))*26 || value > k {
return
}
str = append(str, byte(int('a')+j))
value += j + 1
findSmallestString(value, length, k, index+1, str, res)
str = str[:len(str)-1]
value -= j + 1
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1663.Smallest-String-With-A-Given-Numeric-Value/1663. Smallest String With A Given Numeric Value_test.go | leetcode/1663.Smallest-String-With-A-Given-Numeric-Value/1663. Smallest String With A Given Numeric Value_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1663 struct {
para1663
ans1663
}
// para 是参数
// one 代表第一个参数
type para1663 struct {
n int
k int
}
// ans 是答案
// one 代表第一个答案
type ans1663 struct {
one string
}
func Test_Problem1663(t *testing.T) {
qs := []question1663{
{
para1663{3, 27},
ans1663{"aay"},
},
{
para1663{5, 73},
ans1663{"aaszz"},
},
{
para1663{24, 552},
ans1663{"aaszz"},
},
}
fmt.Printf("------------------------Leetcode Problem 1663------------------------\n")
for _, q := range qs {
_, p := q.ans1663, q.para1663
fmt.Printf("【input】:%v 【output】:%v \n", p, getSmallestString(p.n, 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/1672.Richest-Customer-Wealth/1672. Richest Customer Wealth.go | leetcode/1672.Richest-Customer-Wealth/1672. Richest Customer Wealth.go | package leetcode
func maximumWealth(accounts [][]int) int {
res := 0
for _, banks := range accounts {
sAmount := 0
for _, amount := range banks {
sAmount += amount
}
if sAmount > res {
res = sAmount
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1672.Richest-Customer-Wealth/1672. Richest Customer Wealth_test.go | leetcode/1672.Richest-Customer-Wealth/1672. Richest Customer Wealth_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1672 struct {
para1672
ans1672
}
// para 是参数
// one 代表第一个参数
type para1672 struct {
accounts [][]int
}
// ans 是答案
// one 代表第一个答案
type ans1672 struct {
one int
}
func Test_Problem1672(t *testing.T) {
qs := []question1672{
{
para1672{[][]int{{1, 2, 3}, {3, 2, 1}}},
ans1672{6},
},
{
para1672{[][]int{{1, 5}, {7, 3}, {3, 5}}},
ans1672{10},
},
{
para1672{[][]int{{2, 8, 7}, {7, 1, 3}, {1, 9, 5}}},
ans1672{17},
},
}
fmt.Printf("------------------------Leetcode Problem 1672------------------------\n")
for _, q := range qs {
_, p := q.ans1672, q.para1672
fmt.Printf("【input】:%v 【output】:%v\n", p, maximumWealth(p.accounts))
}
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/1438.Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit.go | leetcode/1438.Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit.go | package leetcode
func longestSubarray(nums []int, limit int) int {
minStack, maxStack, left, res := []int{}, []int{}, 0, 0
for right, num := range nums {
for len(minStack) > 0 && nums[minStack[len(minStack)-1]] > num {
minStack = minStack[:len(minStack)-1]
}
minStack = append(minStack, right)
for len(maxStack) > 0 && nums[maxStack[len(maxStack)-1]] < num {
maxStack = maxStack[:len(maxStack)-1]
}
maxStack = append(maxStack, right)
if len(minStack) > 0 && len(maxStack) > 0 && nums[maxStack[0]]-nums[minStack[0]] > limit {
if left == minStack[0] {
minStack = minStack[1:]
}
if left == maxStack[0] {
maxStack = maxStack[1:]
}
left++
}
if right-left+1 > res {
res = right - left + 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/1438.Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit_test.go | leetcode/1438.Longest-Continuous-Subarray-With-Absolute-Diff-Less-Than-or-Equal-to-Limit/1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1438 struct {
para1438
ans1438
}
// para 是参数
// one 代表第一个参数
type para1438 struct {
nums []int
limit int
}
// ans 是答案
// one 代表第一个答案
type ans1438 struct {
one int
}
func Test_Problem1438(t *testing.T) {
qs := []question1438{
{
para1438{[]int{8, 2, 4, 7}, 4},
ans1438{2},
},
{
para1438{[]int{10, 1, 2, 4, 7, 2}, 5},
ans1438{4},
},
{
para1438{[]int{4, 2, 2, 2, 4, 4, 2, 2}, 0},
ans1438{3},
},
}
fmt.Printf("------------------------Leetcode Problem 1438------------------------\n")
for _, q := range qs {
_, p := q.ans1438, q.para1438
fmt.Printf("【input】:%v 【output】:%v\n", p, longestSubarray(p.nums, p.limit))
}
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/0144.Binary-Tree-Preorder-Traversal/144. Binary Tree Preorder Traversal_test.go | leetcode/0144.Binary-Tree-Preorder-Traversal/144. Binary Tree Preorder Traversal_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question144 struct {
para144
ans144
}
// para 是参数
// one 代表第一个参数
type para144 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans144 struct {
one []int
}
func Test_Problem144(t *testing.T) {
qs := []question144{
{
para144{[]int{}},
ans144{[]int{}},
},
{
para144{[]int{1}},
ans144{[]int{1}},
},
{
para144{[]int{1, structures.NULL, 2, 3}},
ans144{[]int{1, 2, 3}},
},
}
fmt.Printf("------------------------Leetcode Problem 144------------------------\n")
for _, q := range qs {
_, p := q.ans144, q.para144
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", preorderTraversal(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/0144.Binary-Tree-Preorder-Traversal/144. Binary Tree Preorder Traversal.go | leetcode/0144.Binary-Tree-Preorder-Traversal/144. Binary Tree Preorder Traversal.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 preorderTraversal(root *TreeNode) []int {
res := []int{}
if root != nil {
res = append(res, root.Val)
tmp := preorderTraversal(root.Left)
for _, t := range tmp {
res = append(res, t)
}
tmp = preorderTraversal(root.Right)
for _, t := range tmp {
res = append(res, t)
}
}
return res
}
// 解法二 递归
func preorderTraversal1(root *TreeNode) []int {
var result []int
preorder(root, &result)
return result
}
func preorder(root *TreeNode, output *[]int) {
if root != nil {
*output = append(*output, root.Val)
preorder(root.Left, output)
preorder(root.Right, output)
}
}
// 解法三 非递归,用栈模拟递归过程
func preorderTraversal2(root *TreeNode) []int {
if root == nil {
return []int{}
}
stack, res := []*TreeNode{}, []int{}
stack = append(stack, root)
for len(stack) != 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if node != nil {
res = append(res, node.Val)
}
if node.Right != nil {
stack = append(stack, node.Right)
}
if node.Left != nil {
stack = append(stack, node.Left)
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0074.Search-a-2D-Matrix/74. Search a 2D Matrix.go | leetcode/0074.Search-a-2D-Matrix/74. Search a 2D Matrix.go | package leetcode
func searchMatrix(matrix [][]int, target int) bool {
if len(matrix) == 0 {
return false
}
m, low, high := len(matrix[0]), 0, len(matrix[0])*len(matrix)-1
for low <= high {
mid := low + (high-low)>>1
if matrix[mid/m][mid%m] == target {
return true
} else if matrix[mid/m][mid%m] > target {
high = mid - 1
} else {
low = mid + 1
}
}
return false
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0074.Search-a-2D-Matrix/74. Search a 2D Matrix_test.go | leetcode/0074.Search-a-2D-Matrix/74. Search a 2D Matrix_test.go | package leetcode
import (
"fmt"
"testing"
)
type question74 struct {
para74
ans74
}
// para 是参数
// one 代表第一个参数
type para74 struct {
matrix [][]int
target int
}
// ans 是答案
// one 代表第一个答案
type ans74 struct {
one bool
}
func Test_Problem74(t *testing.T) {
qs := []question74{
{
para74{[][]int{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 50}}, 3},
ans74{true},
},
{
para74{[][]int{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 50}}, 13},
ans74{false},
},
}
fmt.Printf("------------------------Leetcode Problem 74------------------------\n")
for _, q := range qs {
_, p := q.ans74, q.para74
fmt.Printf("【input】:%v 【output】:%v\n", p, searchMatrix(p.matrix, p.target))
}
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/0701.Insert-into-a-Binary-Search-Tree/701. Insert into a Binary Search Tree.go | leetcode/0701.Insert-into-a-Binary-Search-Tree/701. Insert into 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 insert(n *TreeNode, val int) *TreeNode {
if n == nil {
return &TreeNode{Val: val}
}
if n.Val < val {
n.Right = insert(n.Right, val)
} else {
n.Left = insert(n.Left, val)
}
return n
}
func insertIntoBST(root *TreeNode, val int) *TreeNode {
return insert(root, val)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0701.Insert-into-a-Binary-Search-Tree/701. Insert into a Binary Search Tree_test.go | leetcode/0701.Insert-into-a-Binary-Search-Tree/701. Insert into a Binary Search Tree_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question701 struct {
para701
ans701
}
// para 是参数
// one 代表第一个参数
type para701 struct {
root []int
val int
}
// ans 是答案
// one 代表第一个答案
type ans701 struct {
one []int
}
func Test_Problem701(t *testing.T) {
qs := []question701{
{
para701{[]int{4, 2, 7, 1, 3}, 5},
ans701{[]int{4, 2, 7, 1, 3, 5}},
},
{
para701{[]int{40, 20, 60, 10, 30, 50, 70}, 25},
ans701{[]int{40, 20, 60, 10, 30, 50, 70, structures.NULL, structures.NULL, 25}},
},
{
para701{[]int{4, 2, 7, 1, 3, structures.NULL, structures.NULL, structures.NULL, structures.NULL, structures.NULL, structures.NULL}, 5},
ans701{[]int{4, 2, 7, 1, 3, 5}},
},
}
fmt.Printf("------------------------Leetcode Problem 701------------------------\n")
for _, q := range qs {
_, p := q.ans701, q.para701
fmt.Printf("【input】:%v ", p)
rootOne := structures.Ints2TreeNode(p.root)
fmt.Printf("【output】:%v \n", structures.Tree2ints(insertIntoBST(rootOne, 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/1190.Reverse-Substrings-Between-Each-Pair-of-Parentheses/1190. Reverse Substrings Between Each Pair of Parentheses.go | leetcode/1190.Reverse-Substrings-Between-Each-Pair-of-Parentheses/1190. Reverse Substrings Between Each Pair of Parentheses.go | package leetcode
func reverseParentheses(s string) string {
pair, stack := make([]int, len(s)), []int{}
for i, b := range s {
if b == '(' {
stack = append(stack, i)
} else if b == ')' {
j := stack[len(stack)-1]
stack = stack[:len(stack)-1]
pair[i], pair[j] = j, i
}
}
res := []byte{}
for i, step := 0, 1; i < len(s); i += step {
if s[i] == '(' || s[i] == ')' {
i = pair[i]
step = -step
} else {
res = append(res, s[i])
}
}
return string(res)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1190.Reverse-Substrings-Between-Each-Pair-of-Parentheses/1190. Reverse Substrings Between Each Pair of Parentheses_test.go | leetcode/1190.Reverse-Substrings-Between-Each-Pair-of-Parentheses/1190. Reverse Substrings Between Each Pair of Parentheses_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1190 struct {
para1190
ans1190
}
// para 是参数
// one 代表第一个参数
type para1190 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans1190 struct {
one string
}
func Test_Problem1190(t *testing.T) {
qs := []question1190{
{
para1190{"(abcd)"},
ans1190{"dcba"},
},
{
para1190{"(u(love)i)"},
ans1190{"iloveu"},
},
{
para1190{"(ed(et(oc))el)"},
ans1190{"leetcode"},
},
{
para1190{"a(bcdefghijkl(mno)p)q"},
ans1190{"apmnolkjihgfedcbq"},
},
}
fmt.Printf("------------------------Leetcode Problem 1190------------------------\n")
for _, q := range qs {
_, p := q.ans1190, q.para1190
fmt.Printf("【input】:%v 【output】:%v\n", p, reverseParentheses(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/1662.Check-If-Two-String-Arrays-are-Equivalent/1662. Check If Two String Arrays are Equivalent_test.go | leetcode/1662.Check-If-Two-String-Arrays-are-Equivalent/1662. Check If Two String Arrays are Equivalent_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1662 struct {
para1662
ans1662
}
// para 是参数
// one 代表第一个参数
type para1662 struct {
word1 []string
word2 []string
}
// ans 是答案
// one 代表第一个答案
type ans1662 struct {
one bool
}
func Test_Problem1662(t *testing.T) {
qs := []question1662{
{
para1662{[]string{"ab", "c"}, []string{"a", "bc"}},
ans1662{true},
},
{
para1662{[]string{"a", "cb"}, []string{"ab", "c"}},
ans1662{false},
},
{
para1662{[]string{"abc", "d", "defg"}, []string{"abcddefg"}},
ans1662{true},
},
}
fmt.Printf("------------------------Leetcode Problem 1662------------------------\n")
for _, q := range qs {
_, p := q.ans1662, q.para1662
fmt.Printf("【input】:%v 【output】:%v \n", p, arrayStringsAreEqual(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/1662.Check-If-Two-String-Arrays-are-Equivalent/1662. Check If Two String Arrays are Equivalent.go | leetcode/1662.Check-If-Two-String-Arrays-are-Equivalent/1662. Check If Two String Arrays are Equivalent.go | package leetcode
func arrayStringsAreEqual(word1 []string, word2 []string) bool {
str1, str2 := "", ""
for i := 0; i < len(word1); i++ {
str1 += word1[i]
}
for i := 0; i < len(word2); i++ {
str2 += word2[i]
}
return str1 == str2
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0114.Flatten-Binary-Tree-to-Linked-List/114. Flatten Binary Tree to Linked List_test.go | leetcode/0114.Flatten-Binary-Tree-to-Linked-List/114. Flatten Binary Tree to Linked List_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question114 struct {
para114
ans114
}
// para 是参数
// one 代表第一个参数
type para114 struct {
one []string
}
// ans 是答案
// one 代表第一个答案
type ans114 struct {
one []string
}
func Test_Problem114(t *testing.T) {
qs := []question114{
{
para114{[]string{"1", "2", "5", "3", "4", "null", "6"}},
ans114{[]string{"1", "null", "2", "null", "3", "null", "4", "null", "5", "null", "6"}},
},
{
para114{[]string{"0"}},
ans114{[]string{"0"}},
},
{
para114{[]string{"1", "2", "3", "4", "5", "6"}},
ans114{[]string{"1", "2", "4", "5", "3", "6", "null"}},
},
}
fmt.Printf("------------------------Leetcode Problem 114------------------------\n")
for _, q := range qs {
_, p := q.ans114, q.para114
fmt.Printf("【input】:%v \n", p)
rootOne := structures.Strings2TreeNode(p.one)
flatten(rootOne)
fmt.Printf("【levelorder output】:%v \n", structures.Tree2LevelOrderStrings(rootOne))
fmt.Printf("【preorder output】:%v \n", structures.Tree2PreOrderStrings(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/0114.Flatten-Binary-Tree-to-Linked-List/114. Flatten Binary Tree to Linked List.go | leetcode/0114.Flatten-Binary-Tree-to-Linked-List/114. Flatten Binary Tree to Linked List.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 flatten(root *TreeNode) {
list := preorder(root)
for i := 1; i < len(list); i++ {
prev, cur := list[i-1], list[i]
prev.Left, prev.Right = nil, cur
}
return
}
func preorder(root *TreeNode) (ans []*TreeNode) {
if root != nil {
ans = append(ans, root)
ans = append(ans, preorder(root.Left)...)
ans = append(ans, preorder(root.Right)...)
}
return
}
// 解法二 递归
func flatten1(root *TreeNode) {
if root == nil || (root.Left == nil && root.Right == nil) {
return
}
flatten(root.Left)
flatten(root.Right)
currRight := root.Right
root.Right = root.Left
root.Left = nil
for root.Right != nil {
root = root.Right
}
root.Right = currRight
}
// 解法三 递归
func flatten2(root *TreeNode) {
if root == nil {
return
}
flatten(root.Right)
if root.Left == nil {
return
}
flatten(root.Left)
p := root.Left
for p.Right != nil {
p = p.Right
}
p.Right = root.Right
root.Right = root.Left
root.Left = nil
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0605.Can-Place-Flowers/605. Can Place Flowers_test.go | leetcode/0605.Can-Place-Flowers/605. Can Place Flowers_test.go | package leetcode
import (
"fmt"
"testing"
)
type question605 struct {
para605
ans605
}
// para 是参数
// one 代表第一个参数
type para605 struct {
flowerbed []int
n int
}
// ans 是答案
// one 代表第一个答案
type ans605 struct {
one bool
}
func Test_Problem605(t *testing.T) {
qs := []question605{
{
para605{[]int{1, 0, 0, 0, 1}, 1},
ans605{true},
},
{
para605{[]int{1, 0, 0, 0, 1}, 2},
ans605{false},
},
{
para605{[]int{1, 0, 0, 0, 0, 1}, 2},
ans605{false},
},
{
para605{[]int{0, 0, 1, 0}, 1},
ans605{true},
},
{
para605{[]int{0, 0, 1, 0, 0}, 1},
ans605{true},
},
{
para605{[]int{1, 0, 0, 1, 0}, 2},
ans605{false},
},
}
fmt.Printf("------------------------Leetcode Problem 605------------------------\n")
for _, q := range qs {
_, p := q.ans605, q.para605
fmt.Printf("【input】:%v 【output】:%v\n", p, canPlaceFlowers(p.flowerbed, 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/0605.Can-Place-Flowers/605. Can Place Flowers.go | leetcode/0605.Can-Place-Flowers/605. Can Place Flowers.go | package leetcode
func canPlaceFlowers(flowerbed []int, n int) bool {
lenth := len(flowerbed)
for i := 0; i < lenth && n > 0; i += 2 {
if flowerbed[i] == 0 {
if i+1 == lenth || flowerbed[i+1] == 0 {
n--
} else {
i++
}
}
}
if n == 0 {
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/0109.Convert-Sorted-List-to-Binary-Search-Tree/109. Convert Sorted List to Binary Search Tree_test.go | leetcode/0109.Convert-Sorted-List-to-Binary-Search-Tree/109. Convert Sorted List to Binary Search Tree_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question109 struct {
para109
ans109
}
// para 是参数
// one 代表第一个参数
type para109 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans109 struct {
one []int
}
func Test_Problem109(t *testing.T) {
qs := []question109{
{
para109{[]int{-10, -3, 0, 5, 9}},
ans109{[]int{0, -10, 5, structures.NULL, -3, structures.NULL, 9}},
},
{
para109{[]int{-10}},
ans109{[]int{-10}},
},
{
para109{[]int{1, 2}},
ans109{[]int{1, 2}},
},
{
para109{[]int{1, 2, 3}},
ans109{[]int{2, 1, 3}},
},
}
fmt.Printf("------------------------Leetcode Problem 109------------------------\n")
for _, q := range qs {
_, p := q.ans109, q.para109
arr := []int{}
structures.T2s(sortedListToBST(structures.Ints2List(p.one)), &arr)
fmt.Printf("【input】:%v 【output】:%v\n", 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/0109.Convert-Sorted-List-to-Binary-Search-Tree/109. Convert Sorted List to Binary Search Tree.go | leetcode/0109.Convert-Sorted-List-to-Binary-Search-Tree/109. Convert Sorted List to Binary Search Tree.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
* }
*/
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sortedListToBST(head *ListNode) *TreeNode {
if head == nil {
return nil
}
if head != nil && head.Next == nil {
return &TreeNode{Val: head.Val, Left: nil, Right: nil}
}
middleNode, preNode := middleNodeAndPreNode(head)
if middleNode == nil {
return nil
}
if preNode != nil {
preNode.Next = nil
}
if middleNode == head {
head = nil
}
return &TreeNode{Val: middleNode.Val, Left: sortedListToBST(head), Right: sortedListToBST(middleNode.Next)}
}
func middleNodeAndPreNode(head *ListNode) (middle *ListNode, pre *ListNode) {
if head == nil || head.Next == nil {
return nil, head
}
p1 := head
p2 := head
for p2.Next != nil && p2.Next.Next != nil {
pre = p1
p1 = p1.Next
p2 = p2.Next.Next
}
return p1, pre
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1512.Number-of-Good-Pairs/1512. Number of Good Pairs_test.go | leetcode/1512.Number-of-Good-Pairs/1512. Number of Good Pairs_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1512 struct {
para1512
ans1512
}
// para 是参数
// one 代表第一个参数
type para1512 struct {
nums []int
}
// ans 是答案
// one 代表第一个答案
type ans1512 struct {
one int
}
func Test_Problem1512(t *testing.T) {
qs := []question1512{
{
para1512{[]int{1, 2, 3, 1, 1, 3}},
ans1512{4},
},
{
para1512{[]int{1, 1, 1, 1}},
ans1512{6},
},
{
para1512{[]int{1, 2, 3}},
ans1512{0},
},
}
fmt.Printf("------------------------Leetcode Problem 1512------------------------\n")
for _, q := range qs {
_, p := q.ans1512, q.para1512
fmt.Printf("【input】:%v 【output】:%v \n", p, numIdenticalPairs(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/1512.Number-of-Good-Pairs/1512. Number of Good Pairs.go | leetcode/1512.Number-of-Good-Pairs/1512. Number of Good Pairs.go | package leetcode
func numIdenticalPairs(nums []int) int {
total := 0
for x := 0; x < len(nums); x++ {
for y := x + 1; y < len(nums); y++ {
if nums[x] == nums[y] {
total++
}
}
}
return total
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0006.ZigZag-Conversion/6. ZigZag Conversion_test.go | leetcode/0006.ZigZag-Conversion/6. ZigZag Conversion_test.go | package leetcode
import (
"fmt"
"testing"
)
type question6 struct {
para6
ans6
}
// para 是参数
// one 代表第一个参数
type para6 struct {
s string
numRows int
}
// ans 是答案
// one 代表第一个答案
type ans6 struct {
one string
}
func Test_Problem6(t *testing.T) {
qs := []question6{
{
para6{"PAYPALISHIRING", 3},
ans6{"PAHNAPLSIIGYIR"},
},
{
para6{"PAYPALISHIRING", 4},
ans6{"PINALSIGYAHRPI"},
},
{
para6{"A", 1},
ans6{"A"},
},
}
fmt.Printf("------------------------Leetcode Problem 6------------------------\n")
for _, q := range qs {
_, p := q.ans6, q.para6
fmt.Printf("【input】:%v 【output】:%v\n", p, convert(p.s, p.numRows))
}
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/0006.ZigZag-Conversion/6. ZigZag Conversion.go | leetcode/0006.ZigZag-Conversion/6. ZigZag Conversion.go | package leetcode
func convert(s string, numRows int) string {
matrix, down, up := make([][]byte, numRows, numRows), 0, numRows-2
for i := 0; i != len(s); {
if down != numRows {
matrix[down] = append(matrix[down], byte(s[i]))
down++
i++
} else if up > 0 {
matrix[up] = append(matrix[up], byte(s[i]))
up--
i++
} else {
up = numRows - 2
down = 0
}
}
solution := make([]byte, 0, len(s))
for _, row := range matrix {
for _, item := range row {
solution = append(solution, item)
}
}
return string(solution)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0124.Binary-Tree-Maximum-Path-Sum/124. Binary Tree Maximum Path Sum_test.go | leetcode/0124.Binary-Tree-Maximum-Path-Sum/124. Binary Tree Maximum Path Sum_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question124 struct {
para124
ans124
}
// para 是参数
// one 代表第一个参数
type para124 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans124 struct {
one int
}
func Test_Problem124(t *testing.T) {
qs := []question124{
{
para124{[]int{}},
ans124{0},
},
{
para124{[]int{1}},
ans124{1},
},
{
para124{[]int{1, 2, 3}},
ans124{6},
},
{
para124{[]int{-10, 9, 20, structures.NULL, structures.NULL, 15, 7}},
ans124{42},
},
}
fmt.Printf("------------------------Leetcode Problem 124------------------------\n")
for _, q := range qs {
_, p := q.ans124, q.para124
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", maxPathSum(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/0124.Binary-Tree-Maximum-Path-Sum/124. Binary Tree Maximum Path Sum.go | leetcode/0124.Binary-Tree-Maximum-Path-Sum/124. Binary Tree Maximum Path Sum.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
* }
*/
func maxPathSum(root *TreeNode) int {
if root == nil {
return 0
}
max := math.MinInt32
getPathSum(root, &max)
return max
}
func getPathSum(root *TreeNode, maxSum *int) int {
if root == nil {
return math.MinInt32
}
left := getPathSum(root.Left, maxSum)
right := getPathSum(root.Right, maxSum)
currMax := max(max(left+root.Val, right+root.Val), root.Val)
*maxSum = max(*maxSum, max(currMax, left+right+root.Val))
return currMax
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0530.Minimum-Absolute-Difference-in-BST/530. Minimum Absolute Difference in BST.go | leetcode/0530.Minimum-Absolute-Difference-in-BST/530. Minimum Absolute Difference in BST.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
* }
*/
func getMinimumDifference(root *TreeNode) int {
res, nodes := math.MaxInt16, -1
dfsBST(root, &res, &nodes)
return res
}
func dfsBST(root *TreeNode, res, pre *int) {
if root == nil {
return
}
dfsBST(root.Left, res, pre)
if *pre != -1 {
*res = min(*res, abs(root.Val-*pre))
}
*pre = root.Val
dfsBST(root.Right, res, pre)
}
func min(a, b int) int {
if a > b {
return b
}
return a
}
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/0530.Minimum-Absolute-Difference-in-BST/530. Minimum Absolute Difference in BST_test.go | leetcode/0530.Minimum-Absolute-Difference-in-BST/530. Minimum Absolute Difference in BST_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question530 struct {
para530
ans530
}
// para 是参数
// one 代表第一个参数
type para530 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans530 struct {
one int
}
func Test_Problem530(t *testing.T) {
qs := []question530{
{
para530{[]int{4, 2, 6, 1, 3}},
ans530{1},
},
{
para530{[]int{1, 0, 48, structures.NULL, structures.NULL, 12, 49}},
ans530{1},
},
{
para530{[]int{90, 69, structures.NULL, 49, 89, structures.NULL, 52}},
ans530{1},
},
}
fmt.Printf("------------------------Leetcode Problem 530------------------------\n")
for _, q := range qs {
_, p := q.ans530, q.para530
fmt.Printf("【input】:%v ", p)
rootOne := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", getMinimumDifference(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/0410.Split-Array-Largest-Sum/410. Split Array Largest Sum.go | leetcode/0410.Split-Array-Largest-Sum/410. Split Array Largest Sum.go | package leetcode
func splitArray(nums []int, m int) int {
maxNum, sum := 0, 0
for _, num := range nums {
sum += num
if num > maxNum {
maxNum = num
}
}
if m == 1 {
return sum
}
low, high := maxNum, sum
for low < high {
mid := low + (high-low)>>1
if calSum(mid, m, nums) {
high = mid
} else {
low = mid + 1
}
}
return low
}
func calSum(mid, m int, nums []int) bool {
sum, count := 0, 0
for _, v := range nums {
sum += v
if sum > mid {
sum = v
count++
// 分成 m 块,只需要插桩 m -1 个
if count > m-1 {
return false
}
}
}
return true
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0410.Split-Array-Largest-Sum/410. Split Array Largest Sum_test.go | leetcode/0410.Split-Array-Largest-Sum/410. Split Array Largest Sum_test.go | package leetcode
import (
"fmt"
"testing"
)
type question410 struct {
para410
ans410
}
// para 是参数
// one 代表第一个参数
type para410 struct {
nums []int
m int
}
// ans 是答案
// one 代表第一个答案
type ans410 struct {
one int
}
func Test_Problem410(t *testing.T) {
qs := []question410{
{
para410{[]int{7, 2, 5, 10, 8}, 2},
ans410{18},
},
}
fmt.Printf("------------------------Leetcode Problem 410------------------------\n")
for _, q := range qs {
_, p := q.ans410, q.para410
fmt.Printf("【input】:%v 【output】:%v\n", p, splitArray(p.nums, p.m))
}
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/0589.N-ary-Tree-Preorder-Traversal/589. N-ary Tree Preorder Traversal.go | leetcode/0589.N-ary-Tree-Preorder-Traversal/589. N-ary Tree Preorder Traversal.go | package leetcode
// Definition for a Node.
type Node struct {
Val int
Children []*Node
}
// 解法一 非递归
func preorder(root *Node) []int {
res := []int{}
if root == nil {
return res
}
stack := []*Node{root}
for len(stack) > 0 {
r := stack[len(stack)-1]
stack = stack[:len(stack)-1]
res = append(res, r.Val)
tmp := []*Node{}
for _, v := range r.Children {
tmp = append([]*Node{v}, tmp...) // 逆序存点
}
stack = append(stack, tmp...)
}
return res
}
// 解法二 递归
func preorder1(root *Node) []int {
res := []int{}
preorderdfs(root, &res)
return res
}
func preorderdfs(root *Node, res *[]int) {
if root != nil {
*res = append(*res, root.Val)
for i := 0; i < len(root.Children); i++ {
preorderdfs(root.Children[i], res)
}
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0589.N-ary-Tree-Preorder-Traversal/589. N-ary Tree Preorder Traversal_test.go | leetcode/0589.N-ary-Tree-Preorder-Traversal/589. N-ary Tree Preorder Traversal_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question589 struct {
para589
ans589
}
// para 是参数
// one 代表第一个参数
type para589 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans589 struct {
one []int
}
func Test_Problem589(t *testing.T) {
qs := []question589{
{
para589{[]int{1, structures.NULL, 3, 2, 4, structures.NULL, 5, 6}},
ans589{[]int{1, 3, 5, 6, 2, 4}},
},
{
para589{[]int{1, structures.NULL, 2, 3, 4, 5, structures.NULL, structures.NULL, 6, 7, structures.NULL, 8, structures.NULL, 9, 10, structures.NULL, structures.NULL, 11, structures.NULL, 12, structures.NULL, 13, structures.NULL, structures.NULL, 14}},
ans589{[]int{1, 2, 3, 6, 7, 11, 14, 4, 8, 12, 5, 9, 13, 10}},
},
}
fmt.Printf("------------------------Leetcode Problem 589------------------------\n")
for _, q := range qs {
_, p := q.ans589, q.para589
fmt.Printf("【input】:%v ", p)
rootOne := int2NaryNode(p.one)
fmt.Printf("【output】:%v \n", preorder(rootOne))
}
fmt.Printf("\n\n\n")
}
func int2NaryNode(nodes []int) *Node {
root := &Node{}
if len(nodes) > 1 {
root.Val = nodes[0]
}
queue := []*Node{}
queue = append(queue, root)
i := 1
count := 0
for i < len(nodes) {
node := queue[0]
childrens := []*Node{}
for ; i < len(nodes) && nodes[i] != structures.NULL; i++ {
tmp := &Node{Val: nodes[i]}
childrens = append(childrens, tmp)
queue = append(queue, tmp)
}
count++
if count%2 == 0 {
queue = queue[1:]
count = 1
}
if node != nil {
node.Children = childrens
}
i++
}
return root
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0384.Shuffle-an-Array/384.Shuffle an Array.go | leetcode/0384.Shuffle-an-Array/384.Shuffle an Array.go | package leetcode
import "math/rand"
type Solution struct {
nums []int
}
func Constructor(nums []int) Solution {
return Solution{
nums: nums,
}
}
/** Resets the array to its original configuration and return it. */
func (this *Solution) Reset() []int {
return this.nums
}
/** Returns a random shuffling of the array. */
func (this *Solution) Shuffle() []int {
arr := make([]int, len(this.nums))
copy(arr, this.nums)
rand.Shuffle(len(arr), func(i, j int) {
arr[i], arr[j] = arr[j], arr[i]
})
return arr
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0384.Shuffle-an-Array/384.Shuffle an Array_test.go | leetcode/0384.Shuffle-an-Array/384.Shuffle an Array_test.go | package leetcode
import (
"fmt"
"testing"
)
type question384 struct {
para384
ans384
}
// para 是参数
type para384 struct {
ops []string
value [][]int
}
// ans 是答案
type ans384 struct {
ans [][]int
}
func Test_Problem384(t *testing.T) {
qs := []question384{
{
para384{ops: []string{"Solution", "shuffle", "reset", "shuffle"}, value: [][]int{{1, 2, 3}, {}, {}, {}}},
ans384{[][]int{nil, {3, 1, 2}, {1, 2, 3}, {1, 3, 2}}},
},
}
fmt.Printf("------------------------Leetcode Problem 384------------------------\n")
for _, q := range qs {
sol := Constructor(nil)
_, p := q.ans384, q.para384
for _, op := range p.ops {
if op == "Solution" {
sol = Constructor(q.value[0])
} else if op == "reset" {
fmt.Printf("【input】:%v 【output】:%v\n", op, sol.Reset())
} else {
fmt.Printf("【input】:%v 【output】:%v\n", op, sol.Shuffle())
}
}
}
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/0720.Longest-Word-in-Dictionary/720. Longest Word in Dictionary.go | leetcode/0720.Longest-Word-in-Dictionary/720. Longest Word in Dictionary.go | package leetcode
import (
"sort"
)
func longestWord(words []string) string {
sort.Strings(words)
mp := make(map[string]bool)
var res string
for _, word := range words {
size := len(word)
if size == 1 || mp[word[:size-1]] {
if size > len(res) {
res = word
}
mp[word] = true
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0720.Longest-Word-in-Dictionary/720. Longest Word in Dictionary_test.go | leetcode/0720.Longest-Word-in-Dictionary/720. Longest Word in Dictionary_test.go | package leetcode
import (
"fmt"
"testing"
)
type question720 struct {
para720
ans720
}
// para 是参数
// one 代表第一个参数
type para720 struct {
w []string
}
// ans 是答案
// one 代表第一个答案
type ans720 struct {
one string
}
func Test_Problem720(t *testing.T) {
qs := []question720{
{
para720{[]string{"w", "wo", "wor", "worl", "world"}},
ans720{"world"},
},
{
para720{[]string{"a", "banana", "app", "appl", "ap", "apply", "apple"}},
ans720{"apple"},
},
}
fmt.Printf("------------------------Leetcode Problem 720------------------------\n")
for _, q := range qs {
_, p := q.ans720, q.para720
fmt.Printf("【input】:%v 【output】:%v\n", p, longestWord(p.w))
}
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/0542.01-Matrix/542. 01 Matrix_test.go | leetcode/0542.01-Matrix/542. 01 Matrix_test.go | package leetcode
import (
"fmt"
"testing"
)
type question542 struct {
para542
ans542
}
// para 是参数
// one 代表第一个参数
type para542 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans542 struct {
one [][]int
}
func Test_Problem542(t *testing.T) {
qs := []question542{
{
para542{[][]int{{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}},
ans542{[][]int{{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}},
},
{
para542{[][]int{{0, 0, 0}, {0, 1, 0}, {1, 1, 1}}},
ans542{[][]int{{0, 0, 0}, {0, 1, 0}, {1, 2, 1}}},
},
{
para542{[][]int{{1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1}, {1, 1, 0, 0, 1, 1}, {1, 1, 0, 0, 1, 1}, {1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1}}},
ans542{[][]int{{4, 3, 2, 2, 3, 4}, {3, 2, 1, 1, 2, 3}, {2, 1, 0, 0, 1, 2}, {2, 1, 0, 0, 1, 2}, {3, 2, 1, 1, 2, 3}, {4, 3, 2, 2, 3, 4}}},
},
}
fmt.Printf("------------------------Leetcode Problem 542------------------------\n")
for _, q := range qs {
_, p := q.ans542, q.para542
fmt.Printf("【input】:%v 【output】:%v\n", p, updateMatrixDP(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/0542.01-Matrix/542. 01 Matrix.go | leetcode/0542.01-Matrix/542. 01 Matrix.go | package leetcode
import (
"math"
)
// 解法一 BFS
func updateMatrixBFS(matrix [][]int) [][]int {
res := make([][]int, len(matrix))
if len(matrix) == 0 || len(matrix[0]) == 0 {
return res
}
queue := make([][]int, 0)
for i := range matrix {
res[i] = make([]int, len(matrix[0]))
for j := range res[i] {
if matrix[i][j] == 0 {
res[i][j] = -1
queue = append(queue, []int{i, j})
}
}
}
level := 1
for len(queue) > 0 {
size := len(queue)
for size > 0 {
size--
node := queue[0]
queue = queue[1:]
i, j := node[0], node[1]
for _, direction := range [][]int{{-1, 0}, {1, 0}, {0, 1}, {0, -1}} {
x := i + direction[0]
y := j + direction[1]
if x < 0 || x >= len(matrix) || y < 0 || y >= len(matrix[0]) || res[x][y] < 0 || res[x][y] > 0 {
continue
}
res[x][y] = level
queue = append(queue, []int{x, y})
}
}
level++
}
for i, row := range res {
for j, cell := range row {
if cell == -1 {
res[i][j] = 0
}
}
}
return res
}
// 解法二 DFS
func updateMatrixDFS(matrix [][]int) [][]int {
result := [][]int{}
if len(matrix) == 0 || len(matrix[0]) == 0 {
return result
}
maxRow, maxCol := len(matrix), len(matrix[0])
for r := 0; r < maxRow; r++ {
for c := 0; c < maxCol; c++ {
if matrix[r][c] == 1 && hasZero(matrix, r, c) == false {
// 将四周没有 0 的 1 特殊处理为最大值
matrix[r][c] = math.MaxInt64
}
}
}
for r := 0; r < maxRow; r++ {
for c := 0; c < maxCol; c++ {
if matrix[r][c] == 1 {
dfsMatrix(matrix, r, c, -1)
}
}
}
return (matrix)
}
// 判断四周是否有 0
func hasZero(matrix [][]int, row, col int) bool {
if row > 0 && matrix[row-1][col] == 0 {
return true
}
if col > 0 && matrix[row][col-1] == 0 {
return true
}
if row < len(matrix)-1 && matrix[row+1][col] == 0 {
return true
}
if col < len(matrix[0])-1 && matrix[row][col+1] == 0 {
return true
}
return false
}
func dfsMatrix(matrix [][]int, row, col, val int) {
// 不超过棋盘氛围,且 val 要比 matrix[row][col] 小
if row < 0 || row >= len(matrix) || col < 0 || col >= len(matrix[0]) || (matrix[row][col] <= val) {
return
}
if val > 0 {
matrix[row][col] = val
}
dfsMatrix(matrix, row-1, col, matrix[row][col]+1)
dfsMatrix(matrix, row, col-1, matrix[row][col]+1)
dfsMatrix(matrix, row+1, col, matrix[row][col]+1)
dfsMatrix(matrix, row, col+1, matrix[row][col]+1)
}
// 解法三 DP
func updateMatrixDP(matrix [][]int) [][]int {
for i, row := range matrix {
for j, val := range row {
if val == 0 {
continue
}
left, top := math.MaxInt16, math.MaxInt16
if i > 0 {
top = matrix[i-1][j] + 1
}
if j > 0 {
left = matrix[i][j-1] + 1
}
matrix[i][j] = min(top, left)
}
}
for i := len(matrix) - 1; i >= 0; i-- {
for j := len(matrix[0]) - 1; j >= 0; j-- {
if matrix[i][j] == 0 {
continue
}
right, bottom := math.MaxInt16, math.MaxInt16
if i < len(matrix)-1 {
bottom = matrix[i+1][j] + 1
}
if j < len(matrix[0])-1 {
right = matrix[i][j+1] + 1
}
matrix[i][j] = min(matrix[i][j], min(bottom, right))
}
}
return matrix
}
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/1704.Determine-if-String-Halves-Are-Alike/1704. Determine if String Halves Are Alike.go | leetcode/1704.Determine-if-String-Halves-Are-Alike/1704. Determine if String Halves Are Alike.go | package leetcode
func halvesAreAlike(s string) bool {
return numVowels(s[len(s)/2:]) == numVowels(s[:len(s)/2])
}
func numVowels(x string) int {
res := 0
for _, c := range x {
switch c {
case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U':
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/1704.Determine-if-String-Halves-Are-Alike/1704. Determine if String Halves Are Alike_test.go | leetcode/1704.Determine-if-String-Halves-Are-Alike/1704. Determine if String Halves Are Alike_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1704 struct {
para1704
ans1704
}
// para 是参数
// one 代表第一个参数
type para1704 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans1704 struct {
one bool
}
func Test_Problem1704(t *testing.T) {
qs := []question1704{
{
para1704{"book"},
ans1704{true},
},
{
para1704{"textbook"},
ans1704{false},
},
{
para1704{"MerryChristmas"},
ans1704{false},
},
{
para1704{"AbCdEfGh"},
ans1704{true},
},
}
fmt.Printf("------------------------Leetcode Problem 1704------------------------\n")
for _, q := range qs {
_, p := q.ans1704, q.para1704
fmt.Printf("【input】:%v 【output】:%v\n", p, halvesAreAlike(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/0447.Number-of-Boomerangs/447. Number of Boomerangs_test.go | leetcode/0447.Number-of-Boomerangs/447. Number of Boomerangs_test.go | package leetcode
import (
"fmt"
"testing"
)
type question447 struct {
para447
ans447
}
// para 是参数
// one 代表第一个参数
type para447 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans447 struct {
one int
}
func Test_Problem447(t *testing.T) {
qs := []question447{
{
para447{[][]int{{0, 0}, {1, 0}, {2, 0}}},
ans447{2},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 447------------------------\n")
for _, q := range qs {
_, p := q.ans447, q.para447
fmt.Printf("【input】:%v 【output】:%v\n", p, numberOfBoomerangs(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/0447.Number-of-Boomerangs/447. Number of Boomerangs.go | leetcode/0447.Number-of-Boomerangs/447. Number of Boomerangs.go | package leetcode
func numberOfBoomerangs(points [][]int) int {
res := 0
for i := 0; i < len(points); i++ {
record := make(map[int]int, len(points))
for j := 0; j < len(points); j++ {
if j != i {
record[dis(points[i], points[j])]++
}
}
for _, r := range record {
res += r * (r - 1)
}
}
return res
}
func dis(pa, pb []int) int {
return (pa[0]-pb[0])*(pa[0]-pb[0]) + (pa[1]-pb[1])*(pa[1]-pb[1])
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0090.Subsets-II/90. Subsets II.go | leetcode/0090.Subsets-II/90. Subsets II.go | package leetcode
import (
"fmt"
"sort"
)
func subsetsWithDup(nums []int) [][]int {
c, res := []int{}, [][]int{}
sort.Ints(nums) // 这里是去重的关键逻辑
for k := 0; k <= len(nums); k++ {
generateSubsetsWithDup(nums, k, 0, c, &res)
}
return res
}
func generateSubsetsWithDup(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++ {
fmt.Printf("i = %v start = %v c = %v\n", i, start, c)
if i > start && nums[i] == nums[i-1] { // 这里是去重的关键逻辑,本次不取重复数字,下次循环可能会取重复数字
continue
}
c = append(c, nums[i])
generateSubsetsWithDup(nums, k, i+1, c, res)
c = c[:len(c)-1]
}
return
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0090.Subsets-II/90. Subsets II_test.go | leetcode/0090.Subsets-II/90. Subsets II_test.go | package leetcode
import (
"fmt"
"testing"
)
type question90 struct {
para90
ans90
}
// para 是参数
// one 代表第一个参数
type para90 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans90 struct {
one [][]int
}
func Test_Problem90(t *testing.T) {
qs := []question90{
{
para90{[]int{}},
ans90{[][]int{{}}},
},
{
para90{[]int{1, 2, 2}},
ans90{[][]int{{}, {1}, {2}, {1, 2}, {2, 2}, {1, 2, 2}}},
},
}
fmt.Printf("------------------------Leetcode Problem 90------------------------\n")
for _, q := range qs {
_, p := q.ans90, q.para90
fmt.Printf("【input】:%v 【output】:%v\n", p, subsetsWithDup(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/1047.Remove-All-Adjacent-Duplicates-In-String/1047. Remove All Adjacent Duplicates In String_test.go | leetcode/1047.Remove-All-Adjacent-Duplicates-In-String/1047. Remove All Adjacent Duplicates In String_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1047 struct {
para1047
ans1047
}
// para 是参数
// one 代表第一个参数
type para1047 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans1047 struct {
one string
}
func Test_Problem1047(t *testing.T) {
qs := []question1047{
{
para1047{"abbaca"},
ans1047{"ca"},
},
}
fmt.Printf("------------------------Leetcode Problem 1047------------------------\n")
for _, q := range qs {
_, p := q.ans1047, q.para1047
fmt.Printf("【input】:%v 【output】:%v\n", p, removeDuplicates1047(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/1047.Remove-All-Adjacent-Duplicates-In-String/1047. Remove All Adjacent Duplicates In String.go | leetcode/1047.Remove-All-Adjacent-Duplicates-In-String/1047. Remove All Adjacent Duplicates In String.go | package leetcode
func removeDuplicates1047(S string) string {
stack := []rune{}
for _, s := range S {
if len(stack) == 0 || len(stack) > 0 && stack[len(stack)-1] != s {
stack = append(stack, s)
} else {
stack = stack[:len(stack)-1]
}
}
return string(stack)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0924.Minimize-Malware-Spread/924. Minimize Malware Spread.go | leetcode/0924.Minimize-Malware-Spread/924. Minimize Malware Spread.go | package leetcode
import (
"math"
"github.com/halfrost/LeetCode-Go/template"
)
func minMalwareSpread(graph [][]int, initial []int) int {
if len(initial) == 0 {
return 0
}
uf, maxLen, maxIdx, uniqInitials, compMap := template.UnionFindCount{}, math.MinInt32, -1, map[int]int{}, map[int][]int{}
uf.Init(len(graph))
for i := range graph {
for j := i + 1; j < len(graph); j++ {
if graph[i][j] == 1 {
uf.Union(i, j)
}
}
}
for _, i := range initial {
compMap[uf.Find(i)] = append(compMap[uf.Find(i)], i)
}
for _, v := range compMap {
if len(v) == 1 {
uniqInitials[v[0]] = v[0]
}
}
if len(uniqInitials) == 0 {
smallestIdx := initial[0]
for _, i := range initial {
if i < smallestIdx {
smallestIdx = i
}
}
return smallestIdx
}
for _, i := range initial {
if _, ok := uniqInitials[i]; ok {
size := uf.Count()[uf.Find(i)]
if maxLen < size {
maxLen, maxIdx = size, i
} else if maxLen == size {
if i < maxIdx {
maxIdx = i
}
}
}
}
return maxIdx
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0924.Minimize-Malware-Spread/924. Minimize Malware Spread_test.go | leetcode/0924.Minimize-Malware-Spread/924. Minimize Malware Spread_test.go | package leetcode
import (
"fmt"
"testing"
)
type question924 struct {
para924
ans924
}
// para 是参数
// one 代表第一个参数
type para924 struct {
graph [][]int
initial []int
}
// ans 是答案
// one 代表第一个答案
type ans924 struct {
one int
}
func Test_Problem924(t *testing.T) {
qs := []question924{
{
para924{[][]int{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 1}, {0, 0, 1, 1}}, []int{3, 1}},
ans924{3},
},
{
para924{[][]int{{1, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0}, {0, 0, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0}, {0, 0, 0, 1, 1, 0}, {0, 0, 0, 0, 0, 1}}, []int{5, 0}},
ans924{0},
},
{
para924{[][]int{{1, 1, 1}, {1, 1, 1}, {1, 1, 1}}, []int{1, 2}},
ans924{1},
},
{
para924{[][]int{{1, 1, 0}, {1, 1, 0}, {0, 0, 1}}, []int{0, 1}},
ans924{0},
},
{
para924{[][]int{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, []int{0, 2}},
ans924{0},
},
}
fmt.Printf("------------------------Leetcode Problem 924------------------------\n")
for _, q := range qs {
_, p := q.ans924, q.para924
fmt.Printf("【input】:%v 【output】:%v\n", p, minMalwareSpread(p.graph, p.initial))
}
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/0225.Implement-Stack-using-Queues/225. Implement Stack using Queues.go | leetcode/0225.Implement-Stack-using-Queues/225. Implement Stack using Queues.go | package leetcode
type MyStack struct {
enque []int
deque []int
}
/** Initialize your data structure here. */
func Constructor225() MyStack {
return MyStack{[]int{}, []int{}}
}
/** Push element x onto stack. */
func (this *MyStack) Push(x int) {
this.enque = append(this.enque, x)
}
/** Removes the element on top of the stack and returns that element. */
func (this *MyStack) Pop() int {
length := len(this.enque)
for i := 0; i < length-1; i++ {
this.deque = append(this.deque, this.enque[0])
this.enque = this.enque[1:]
}
topEle := this.enque[0]
this.enque = this.deque
this.deque = nil
return topEle
}
/** Get the top element. */
func (this *MyStack) Top() int {
topEle := this.Pop()
this.enque = append(this.enque, topEle)
return topEle
}
/** Returns whether the stack is empty. */
func (this *MyStack) Empty() bool {
if len(this.enque) == 0 {
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/0225.Implement-Stack-using-Queues/225. Implement Stack using Queues_test.go | leetcode/0225.Implement-Stack-using-Queues/225. Implement Stack using Queues_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem225(t *testing.T) {
obj := Constructor225()
fmt.Printf("obj = %v\n", obj)
param5 := obj.Empty()
fmt.Printf("param_5 = %v\n", param5)
obj.Push(2)
fmt.Printf("obj = %v\n", obj)
obj.Push(10)
fmt.Printf("obj = %v\n", obj)
param2 := obj.Pop()
fmt.Printf("param_2 = %v\n", param2)
param3 := obj.Top()
fmt.Printf("param_3 = %v\n", param3)
param4 := obj.Empty()
fmt.Printf("param_4 = %v\n", param4)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0551.Student-Attendance-Record-I/551.Student Attendance Record I.go | leetcode/0551.Student-Attendance-Record-I/551.Student Attendance Record I.go | package leetcode
func checkRecord(s string) bool {
numsA, maxL, numsL := 0, 0, 0
for _, v := range s {
if v == 'L' {
numsL++
} else {
if numsL > maxL {
maxL = numsL
}
numsL = 0
if v == 'A' {
numsA++
}
}
}
if numsL > maxL {
maxL = numsL
}
return numsA < 2 && maxL < 3
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0551.Student-Attendance-Record-I/551.Student Attendance Record I_test.go | leetcode/0551.Student-Attendance-Record-I/551.Student Attendance Record I_test.go | package leetcode
import (
"fmt"
"testing"
)
type question551 struct {
para551
ans551
}
// para 是参数
type para551 struct {
s string
}
// ans 是答案
type ans551 struct {
ans bool
}
func Test_Problem551(t *testing.T) {
qs := []question551{
{
para551{"PPALLP"},
ans551{true},
},
{
para551{"PPALLL"},
ans551{false},
},
}
fmt.Printf("------------------------Leetcode Problem 551------------------------\n")
for _, q := range qs {
_, p := q.ans551, q.para551
fmt.Printf("【input】:%v 【output】:%v \n", p, checkRecord(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/0504.Base-7/504.Base 7_test.go | leetcode/0504.Base-7/504.Base 7_test.go | package leetcode
import (
"fmt"
"testing"
)
type question504 struct {
para504
ans504
}
// para 是参数
type para504 struct {
num int
}
// ans 是答案
type ans504 struct {
ans string
}
func Test_Problem504(t *testing.T) {
qs := []question504{
{
para504{100},
ans504{"202"},
},
{
para504{-7},
ans504{"-10"},
},
}
fmt.Printf("------------------------Leetcode Problem 504------------------------\n")
for _, q := range qs {
_, p := q.ans504, q.para504
fmt.Printf("【input】:%v ", p.num)
fmt.Printf("【output】:%v \n", convertToBase7(p.num))
}
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/0504.Base-7/504.Base 7.go | leetcode/0504.Base-7/504.Base 7.go | package leetcode
import "strconv"
func convertToBase7(num int) string {
if num == 0 {
return "0"
}
negative := false
if num < 0 {
negative = true
num = -num
}
var ans string
var nums []int
for num != 0 {
remainder := num % 7
nums = append(nums, remainder)
num = num / 7
}
if negative {
ans += "-"
}
for i := len(nums) - 1; i >= 0; i-- {
ans += strconv.Itoa(nums[i])
}
return ans
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0791.Custom-Sort-String/791. Custom Sort String_test.go | leetcode/0791.Custom-Sort-String/791. Custom Sort String_test.go | package leetcode
import (
"fmt"
"testing"
)
type question791 struct {
para791
ans791
}
// para 是参数
// one 代表第一个参数
type para791 struct {
order string
str string
}
// ans 是答案
// one 代表第一个答案
type ans791 struct {
one string
}
func Test_Problem791(t *testing.T) {
qs := []question791{
{
para791{"cba", "abcd"},
ans791{"cbad"},
},
}
fmt.Printf("------------------------Leetcode Problem 791------------------------\n")
for _, q := range qs {
_, p := q.ans791, q.para791
fmt.Printf("【input】:%v 【output】:%v\n", p, customSortString(p.order, p.str))
}
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/0791.Custom-Sort-String/791. Custom Sort String.go | leetcode/0791.Custom-Sort-String/791. Custom Sort String.go | package leetcode
import "sort"
func customSortString(order string, str string) string {
magic := map[byte]int{}
for i := range order {
magic[order[i]] = i - 30
}
byteSlice := []byte(str)
sort.Slice(byteSlice, func(i, j int) bool {
return magic[byteSlice[i]] < magic[byteSlice[j]]
})
return string(byteSlice)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1678.Goal-Parser-Interpretation/1678. Goal Parser Interpretation.go | leetcode/1678.Goal-Parser-Interpretation/1678. Goal Parser Interpretation.go | package leetcode
func interpret(command string) string {
if command == "" {
return ""
}
res := ""
for i := 0; i < len(command); i++ {
if command[i] == 'G' {
res += "G"
} else {
if command[i] == '(' && command[i+1] == 'a' {
res += "al"
i += 3
} else {
res += "o"
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/1678.Goal-Parser-Interpretation/1678. Goal Parser Interpretation_test.go | leetcode/1678.Goal-Parser-Interpretation/1678. Goal Parser Interpretation_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1678 struct {
para1678
ans1678
}
// para 是参数
// one 代表第一个参数
type para1678 struct {
command string
}
// ans 是答案
// one 代表第一个答案
type ans1678 struct {
one string
}
func Test_Problem1678(t *testing.T) {
qs := []question1678{
{
para1678{"G()(al)"},
ans1678{"Goal"},
},
{
para1678{"G()()()()(al)"},
ans1678{"Gooooal"},
},
{
para1678{"(al)G(al)()()G"},
ans1678{"alGalooG"},
},
}
fmt.Printf("------------------------Leetcode Problem 1678------------------------\n")
for _, q := range qs {
_, p := q.ans1678, q.para1678
fmt.Printf("【input】:%v 【output】:%v\n", p, interpret(p.command))
}
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/1657.Determine-if-Two-Strings-Are-Close/1657. Determine if Two Strings Are Close.go | leetcode/1657.Determine-if-Two-Strings-Are-Close/1657. Determine if Two Strings Are Close.go | package leetcode
import (
"sort"
)
func closeStrings(word1 string, word2 string) bool {
if len(word1) != len(word2) {
return false
}
freqCount1, freqCount2 := make([]int, 26), make([]int, 26)
for _, c := range word1 {
freqCount1[c-97]++
}
for _, c := range word2 {
freqCount2[c-97]++
}
for i := 0; i < 26; i++ {
if (freqCount1[i] == freqCount2[i]) ||
(freqCount1[i] > 0 && freqCount2[i] > 0) {
continue
}
return false
}
sort.Ints(freqCount1)
sort.Ints(freqCount2)
for i := 0; i < 26; i++ {
if freqCount1[i] != freqCount2[i] {
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/1657.Determine-if-Two-Strings-Are-Close/1657. Determine if Two Strings Are Close_test.go | leetcode/1657.Determine-if-Two-Strings-Are-Close/1657. Determine if Two Strings Are Close_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1657 struct {
para1657
ans1657
}
// para 是参数
// one 代表第一个参数
type para1657 struct {
word1 string
word2 string
}
// ans 是答案
// one 代表第一个答案
type ans1657 struct {
one bool
}
func Test_Problem1657(t *testing.T) {
qs := []question1657{
{
para1657{"abc", "bca"},
ans1657{true},
},
{
para1657{"a", "aa"},
ans1657{false},
},
{
para1657{"cabbba", "abbccc"},
ans1657{true},
},
{
para1657{"cabbba", "aabbss"},
ans1657{false},
},
{
para1657{"uau", "ssx"},
ans1657{false},
},
{
para1657{"uuukuuuukkuusuususuuuukuskuusuuusuusuuuuuuk", "kssskkskkskssskksskskksssssksskksskskksksuu"},
ans1657{false},
},
}
fmt.Printf("------------------------Leetcode Problem 1657------------------------\n")
for _, q := range qs {
_, p := q.ans1657, q.para1657
fmt.Printf("【input】:%v 【output】:%v \n", p, closeStrings(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/0892.Surface-Area-of-3D-Shapes/892. Surface Area of 3D Shapes.go | leetcode/0892.Surface-Area-of-3D-Shapes/892. Surface Area of 3D Shapes.go | package leetcode
func surfaceArea(grid [][]int) int {
area := 0
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[0]); j++ {
if grid[i][j] == 0 {
continue
}
area += grid[i][j]*4 + 2
// up
if i > 0 {
m := min(grid[i][j], grid[i-1][j])
area -= m
}
// down
if i < len(grid)-1 {
m := min(grid[i][j], grid[i+1][j])
area -= m
}
// left
if j > 0 {
m := min(grid[i][j], grid[i][j-1])
area -= m
}
// right
if j < len(grid[i])-1 {
m := min(grid[i][j], grid[i][j+1])
area -= m
}
}
}
return area
}
func min(a, 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/0892.Surface-Area-of-3D-Shapes/892. Surface Area of 3D Shapes_test.go | leetcode/0892.Surface-Area-of-3D-Shapes/892. Surface Area of 3D Shapes_test.go | package leetcode
import (
"fmt"
"testing"
)
type question892 struct {
para892
ans892
}
// para 是参数
// one 代表第一个参数
type para892 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans892 struct {
one int
}
func Test_Problem892(t *testing.T) {
qs := []question892{
{
para892{[][]int{{2}}},
ans892{10},
},
{
para892{[][]int{{1, 2}, {3, 4}}},
ans892{34},
},
{
para892{[][]int{{1, 0}, {0, 2}}},
ans892{16},
},
{
para892{[][]int{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}},
ans892{32},
},
{
para892{[][]int{{2, 2, 2}, {2, 1, 2}, {2, 2, 2}}},
ans892{46},
},
}
fmt.Printf("------------------------Leetcode Problem 892------------------------\n")
for _, q := range qs {
_, p := q.ans892, q.para892
fmt.Printf("【input】:%v 【output】:%v\n", p, surfaceArea(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/structures/Heap.go | structures/Heap.go | package structures
// intHeap 实现了最小堆 heap 的接口
type intHeap []int
func (h intHeap) Len() int {
return len(h)
}
func (h intHeap) Less(i, j int) bool {
return h[i] < h[j]
}
func (h intHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
}
func (h *intHeap) Push(x interface{}) {
// Push 使用 *h,是因为
// Push 增加了 h 的长度
*h = append(*h, x.(int))
}
func (h *intHeap) Pop() interface{} {
// Pop 使用 *h ,是因为
// Pop 减短了 h 的长度
res := (*h)[len(*h)-1]
*h = (*h)[:len(*h)-1]
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/Stack_test.go | structures/Stack_test.go | package structures
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_Stack(t *testing.T) {
ast := assert.New(t)
s := NewStack()
ast.True(s.IsEmpty(), "检查新建的 s 是否为空")
start, end := 0, 100
for i := start; i < end; i++ {
s.Push(i)
ast.Equal(i-start+1, s.Len(), "Push 后检查 q 的长度。")
}
for i := end - 1; i >= start; i-- {
ast.Equal(i, s.Pop(), "从 s 中 pop 出数来。")
}
ast.True(s.IsEmpty(), "检查 Pop 完毕后的 s 是否为空")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/ListNode.go | structures/ListNode.go | package structures
import (
"fmt"
)
// ListNode 是链接节点
// 这个不能复制到*_test.go文件中。会导致Travis失败
type ListNode struct {
Val int
Next *ListNode
}
// List2Ints convert List to []int
func List2Ints(head *ListNode) []int {
// 链条深度限制,链条深度超出此限制,会 panic
limit := 100
times := 0
res := []int{}
for head != nil {
times++
if times > limit {
msg := fmt.Sprintf("链条深度超过%d,可能出现环状链条。请检查错误,或者放宽 l2s 函数中 limit 的限制。", limit)
panic(msg)
}
res = append(res, head.Val)
head = head.Next
}
return res
}
// Ints2List convert []int to List
func Ints2List(nums []int) *ListNode {
if len(nums) == 0 {
return nil
}
l := &ListNode{}
t := l
for _, v := range nums {
t.Next = &ListNode{Val: v}
t = t.Next
}
return l.Next
}
// GetNodeWith returns the first node with val
func (l *ListNode) GetNodeWith(val int) *ListNode {
res := l
for res != nil {
if res.Val == val {
break
}
res = res.Next
}
return res
}
// Ints2ListWithCycle returns a list whose tail point to pos-indexed node
// head's index is 0
// if pos = -1, no cycle
func Ints2ListWithCycle(nums []int, pos int) *ListNode {
head := Ints2List(nums)
if pos == -1 {
return head
}
c := head
for pos > 0 {
c = c.Next
pos--
}
tail := c
for tail.Next != nil {
tail = tail.Next
}
tail.Next = c
return head
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/Interval_test.go | structures/Interval_test.go | package structures
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_Interval2Ints(t *testing.T) {
ast := assert.New(t)
actual := Interval2Ints(Interval{Start: 1, End: 2})
expected := []int{1, 2}
ast.Equal(expected, actual)
}
func Test_IntervalSlice2Intss(t *testing.T) {
ast := assert.New(t)
actual := IntervalSlice2Intss(
[]Interval{
{
Start: 1,
End: 2,
},
{
Start: 3,
End: 4,
},
},
)
expected := [][]int{
{1, 2},
{3, 4},
}
ast.Equal(expected, actual)
}
func Test_Intss2IntervalSlice(t *testing.T) {
ast := assert.New(t)
expected := []Interval{
{
Start: 1,
End: 2,
},
{
Start: 3,
End: 4,
},
}
actual := Intss2IntervalSlice([][]int{
{1, 2},
{3, 4},
},
)
ast.Equal(expected, actual)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/Queue_test.go | structures/Queue_test.go | package structures
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_Queue(t *testing.T) {
ast := assert.New(t)
q := NewQueue()
ast.True(q.IsEmpty(), "检查新建的 q 是否为空")
start, end := 0, 100
for i := start; i < end; i++ {
q.Push(i)
ast.Equal(i-start+1, q.Len(), "Push 后检查 q 的长度。")
}
for i := start; i < end; i++ {
ast.Equal(i, q.Pop(), "从 q 中 pop 出数来。")
}
ast.True(q.IsEmpty(), "检查 Pop 完毕后的 q 是否为空")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/Interval.go | structures/Interval.go | package structures
// Interval 提供区间表示
type Interval struct {
Start int
End int
}
// Interval2Ints 把 Interval 转换成 整型切片
func Interval2Ints(i Interval) []int {
return []int{i.Start, i.End}
}
// IntervalSlice2Intss 把 []Interval 转换成 [][]int
func IntervalSlice2Intss(is []Interval) [][]int {
res := make([][]int, 0, len(is))
for i := range is {
res = append(res, Interval2Ints(is[i]))
}
return res
}
// Intss2IntervalSlice 把 [][]int 转换成 []Interval
func Intss2IntervalSlice(intss [][]int) []Interval {
res := make([]Interval, 0, len(intss))
for _, ints := range intss {
res = append(res, Interval{Start: ints[0], End: ints[1]})
}
return res
}
// QuickSort define
func QuickSort(a []Interval, lo, hi int) {
if lo >= hi {
return
}
p := partitionSort(a, lo, hi)
QuickSort(a, lo, p-1)
QuickSort(a, p+1, hi)
}
func partitionSort(a []Interval, lo, hi int) int {
pivot := a[hi]
i := lo - 1
for j := lo; j < hi; j++ {
if (a[j].Start < pivot.Start) || (a[j].Start == pivot.Start && a[j].End < pivot.End) {
i++
a[j], a[i] = a[i], a[j]
}
}
a[i+1], a[hi] = a[hi], a[i+1]
return i + 1
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/ListNode_test.go | structures/ListNode_test.go | package structures
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_l2s(t *testing.T) {
ast := assert.New(t)
ast.Equal([]int{}, List2Ints(nil), "输入nil,没有返回[]int{}")
one2three := &ListNode{
Val: 1,
Next: &ListNode{
Val: 2,
Next: &ListNode{
Val: 3,
},
},
}
ast.Equal([]int{1, 2, 3}, List2Ints(one2three), "没有成功地转换成[]int")
limit := 100
overLimitList := Ints2List(make([]int, limit+1))
ast.Panics(func() { List2Ints(overLimitList) }, "转换深度超过 %d 限制的链条,没有 panic", limit)
}
func Test_s2l(t *testing.T) {
ast := assert.New(t)
ast.Nil(Ints2List([]int{}), "输入[]int{},没有返回nil")
ln := Ints2List([]int{1, 2, 3, 4, 5, 6, 7, 8, 9})
i := 1
for ln != nil {
ast.Equal(i, ln.Val, "对应的值不对")
ln = ln.Next
i++
}
}
func Test_getNodeWith(t *testing.T) {
ast := assert.New(t)
//
ln := Ints2List([]int{1, 2, 3, 4, 5, 6, 7, 8, 9})
val := 10
node := &ListNode{
Val: val,
}
tail := ln
for tail.Next != nil {
tail = tail.Next
}
tail.Next = node
expected := node
actual := ln.GetNodeWith(val)
ast.Equal(expected, actual)
}
func Test_Ints2ListWithCycle(t *testing.T) {
ast := assert.New(t)
ints := []int{1, 2, 3}
l := Ints2ListWithCycle(ints, -1)
ast.Equal(ints, List2Ints(l))
l = Ints2ListWithCycle(ints, 1)
ast.Panics(func() { List2Ints(l) })
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/Point_test.go | structures/Point_test.go | package structures
import (
"reflect"
"testing"
)
func Test_Intss2Points(t *testing.T) {
type args struct {
points [][]int
}
tests := []struct {
name string
args args
want []Point
}{
{
"测试 [][]int 转换成 []Point ",
args{
[][]int{
{1, 0},
{2, 0},
{3, 0},
{4, 0},
{5, 0},
},
},
[]Point{
{X: 1, Y: 0},
{X: 2, Y: 0},
{X: 3, Y: 0},
{X: 4, Y: 0},
{X: 5, Y: 0},
},
},
}
for _, tt := range tests {
if got := Intss2Points(tt.args.points); !reflect.DeepEqual(got, tt.want) {
t.Errorf("%q. intss2Points() = %v, want %v", tt.name, got, tt.want)
}
}
}
func Test_Points2Intss(t *testing.T) {
type args struct {
points []Point
}
tests := []struct {
name string
args args
want [][]int
}{
{
"测试 [][]int 转换成 []Point ",
args{
[]Point{
{X: 1, Y: 0},
{X: 2, Y: 0},
{X: 3, Y: 0},
{X: 4, Y: 0},
{X: 5, Y: 0},
},
},
[][]int{
{1, 0},
{2, 0},
{3, 0},
{4, 0},
{5, 0},
},
},
}
for _, tt := range tests {
if got := Points2Intss(tt.args.points); !reflect.DeepEqual(got, tt.want) {
t.Errorf("%q. Points2Intss() = %v, want %v", tt.name, got, tt.want)
}
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/Queue.go | structures/Queue.go | package structures
// Queue 是用于存放 int 的队列
type Queue struct {
nums []int
}
// NewQueue 返回 *kit.Queue
func NewQueue() *Queue {
return &Queue{nums: []int{}}
}
// Push 把 n 放入队列
func (q *Queue) Push(n int) {
q.nums = append(q.nums, n)
}
// Pop 从 q 中取出最先进入队列的值
func (q *Queue) Pop() int {
res := q.nums[0]
q.nums = q.nums[1:]
return res
}
// Len 返回 q 的长度
func (q *Queue) Len() int {
return len(q.nums)
}
// IsEmpty 反馈 q 是否为空
func (q *Queue) IsEmpty() bool {
return q.Len() == 0
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/NestedInterger_test.go | structures/NestedInterger_test.go | package structures
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_NestedInteger(t *testing.T) {
ast := assert.New(t)
n := NestedInteger{}
ast.True(n.IsInteger())
n.SetInteger(1)
ast.Equal(1, n.GetInteger())
elem := NestedInteger{Num: 1}
expected := NestedInteger{
Num: 1,
Ns: []*NestedInteger{&elem},
}
n.Add(elem)
ast.Equal(expected, n)
ast.Equal(expected.Ns, n.GetList())
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/Point.go | structures/Point.go | package structures
// Point 定义了一个二维坐标点
type Point struct {
X, Y int
}
// Intss2Points 把 [][]int 转换成 []Point
func Intss2Points(points [][]int) []Point {
res := make([]Point, len(points))
for i, p := range points {
res[i] = Point{
X: p[0],
Y: p[1],
}
}
return res
}
// Points2Intss 把 []Point 转换成 [][]int
func Points2Intss(points []Point) [][]int {
res := make([][]int, len(points))
for i, p := range points {
res[i] = []int{p.X, p.Y}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/TreeNode.go | structures/TreeNode.go | package structures
import (
"fmt"
"strconv"
)
// TreeNode is tree's node
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// NULL 方便添加测试数据
var NULL = -1 << 63
// Ints2TreeNode 利用 []int 生成 *TreeNode
func Ints2TreeNode(ints []int) *TreeNode {
n := len(ints)
if n == 0 {
return nil
}
root := &TreeNode{
Val: ints[0],
}
queue := make([]*TreeNode, 1, n*2)
queue[0] = root
i := 1
for i < n {
node := queue[0]
queue = queue[1:]
if i < n && ints[i] != NULL {
node.Left = &TreeNode{Val: ints[i]}
queue = append(queue, node.Left)
}
i++
if i < n && ints[i] != NULL {
node.Right = &TreeNode{Val: ints[i]}
queue = append(queue, node.Right)
}
i++
}
return root
}
// GetTargetNode 返回 Val = target 的 TreeNode
// root 中一定有 node.Val = target
func GetTargetNode(root *TreeNode, target int) *TreeNode {
if root == nil || root.Val == target {
return root
}
res := GetTargetNode(root.Left, target)
if res != nil {
return res
}
return GetTargetNode(root.Right, target)
}
func indexOf(val int, nums []int) int {
for i, v := range nums {
if v == val {
return i
}
}
msg := fmt.Sprintf("%d 不存在于 %v 中", val, nums)
panic(msg)
}
// PreIn2Tree 把 preorder 和 inorder 切片转换成 二叉树
func PreIn2Tree(pre, in []int) *TreeNode {
if len(pre) != len(in) {
panic("preIn2Tree 中两个切片的长度不相等")
}
if len(in) == 0 {
return nil
}
res := &TreeNode{
Val: pre[0],
}
if len(in) == 1 {
return res
}
idx := indexOf(res.Val, in)
res.Left = PreIn2Tree(pre[1:idx+1], in[:idx])
res.Right = PreIn2Tree(pre[idx+1:], in[idx+1:])
return res
}
// InPost2Tree 把 inorder 和 postorder 切片转换成 二叉树
func InPost2Tree(in, post []int) *TreeNode {
if len(post) != len(in) {
panic("inPost2Tree 中两个切片的长度不相等")
}
if len(in) == 0 {
return nil
}
res := &TreeNode{
Val: post[len(post)-1],
}
if len(in) == 1 {
return res
}
idx := indexOf(res.Val, in)
res.Left = InPost2Tree(in[:idx], post[:idx])
res.Right = InPost2Tree(in[idx+1:], post[idx:len(post)-1])
return res
}
// Tree2Preorder 把 二叉树 转换成 preorder 的切片
func Tree2Preorder(root *TreeNode) []int {
if root == nil {
return nil
}
if root.Left == nil && root.Right == nil {
return []int{root.Val}
}
res := []int{root.Val}
res = append(res, Tree2Preorder(root.Left)...)
res = append(res, Tree2Preorder(root.Right)...)
return res
}
// Tree2Inorder 把 二叉树转换成 inorder 的切片
func Tree2Inorder(root *TreeNode) []int {
if root == nil {
return nil
}
if root.Left == nil && root.Right == nil {
return []int{root.Val}
}
res := Tree2Inorder(root.Left)
res = append(res, root.Val)
res = append(res, Tree2Inorder(root.Right)...)
return res
}
// Tree2Postorder 把 二叉树 转换成 postorder 的切片
func Tree2Postorder(root *TreeNode) []int {
if root == nil {
return nil
}
if root.Left == nil && root.Right == nil {
return []int{root.Val}
}
res := Tree2Postorder(root.Left)
res = append(res, Tree2Postorder(root.Right)...)
res = append(res, root.Val)
return res
}
// Equal return ture if tn == a
func (tn *TreeNode) Equal(a *TreeNode) bool {
if tn == nil && a == nil {
return true
}
if tn == nil || a == nil || tn.Val != a.Val {
return false
}
return tn.Left.Equal(a.Left) && tn.Right.Equal(a.Right)
}
// Tree2ints 把 *TreeNode 按照行还原成 []int
func Tree2ints(tn *TreeNode) []int {
res := make([]int, 0, 1024)
queue := []*TreeNode{tn}
for len(queue) > 0 {
size := len(queue)
for i := 0; i < size; i++ {
nd := queue[i]
if nd == nil {
res = append(res, NULL)
} else {
res = append(res, nd.Val)
queue = append(queue, nd.Left, nd.Right)
}
}
queue = queue[size:]
}
i := len(res)
for i > 0 && res[i-1] == NULL {
i--
}
return res[:i]
}
// T2s converts *TreeNode to []int
func T2s(head *TreeNode, array *[]int) {
fmt.Printf("运行到这里了 head = %v array = %v\n", head, array)
// fmt.Printf("****array = %v\n", array)
// fmt.Printf("****head = %v\n", head.Val)
*array = append(*array, head.Val)
if head.Left != nil {
T2s(head.Left, array)
}
if head.Right != nil {
T2s(head.Right, array)
}
}
// Strings2TreeNode converts []string to *TreeNode
func Strings2TreeNode(strs []string) *TreeNode {
n := len(strs)
if n == 0 {
return nil
}
x, _ := strconv.Atoi(strs[0])
root := &TreeNode{Val: x}
queue := make([]*TreeNode, 1, n<<1)
queue[0] = root
i := 1
for i < n {
node := queue[0]
queue = queue[1:]
if i < n && strs[i] != "null" {
x, _ = strconv.Atoi(strs[i])
node.Left = &TreeNode{Val: x}
queue = append(queue, node.Left)
}
i++
if i < n && strs[i] != "null" {
x, _ = strconv.Atoi(strs[i])
node.Right = &TreeNode{Val: x}
queue = append(queue, node.Right)
}
i++
}
return root
}
// Tree2LevelOrderStrings converts *TreeNode into []string by level order traversal.
func Tree2LevelOrderStrings(root *TreeNode) []string {
var ans []string
if root == nil {
return ans
}
queue := []*TreeNode{root}
var level int
for level = 0; len(queue) > 0; level++ {
size := len(queue)
for i := 0; i < size; i++ {
node := queue[i]
if node == nil {
ans = append(ans, "null")
} else {
ans = append(ans, strconv.Itoa(node.Val))
if node.Left != nil || node.Right != nil {
queue = append(queue, node.Left, node.Right)
}
}
}
queue = queue[size:]
}
level--
return ans
}
// Tree2PreOrderStrings converts *TreeNode into []string by preorder traversal.
func Tree2PreOrderStrings(root *TreeNode) []string {
var ans []string
if root == nil {
return ans
}
stack := []*TreeNode{root}
node := root
for len(stack) > 0 {
if node == nil {
ans = append(ans, "null")
}
for node != nil {
ans = append(ans, strconv.Itoa(node.Val))
stack = append(stack, node)
node = node.Left
}
node = stack[len(stack)-1].Right
stack = stack[:len(stack)-1]
}
return ans
}
| 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.