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/0054.Spiral-Matrix/54. Spiral Matrix_test.go | leetcode/0054.Spiral-Matrix/54. Spiral Matrix_test.go | package leetcode
import (
"fmt"
"testing"
)
type question54 struct {
para54
ans54
}
// para 是参数
// one 代表第一个参数
type para54 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans54 struct {
one []int
}
func Test_Problem54(t *testing.T) {
qs := []question54{
{
para54{[][]int{{3}, {2}}},
ans54{[]int{3, 2}},
},
{
para54{[][]int{{2, 3}}},
ans54{[]int{2, 3}},
},
{
para54{[][]int{{1}}},
ans54{[]int{1}},
},
{
para54{[][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}},
ans54{[]int{1, 2, 3, 6, 9, 8, 7, 4, 5}},
},
{
para54{[][]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}},
ans54{[]int{1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7}},
},
}
fmt.Printf("------------------------Leetcode Problem 54------------------------\n")
for _, q := range qs {
_, p := q.ans54, q.para54
fmt.Printf("【input】:%v 【output】:%v\n", p, spiralOrder(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/0054.Spiral-Matrix/54. Spiral Matrix.go | leetcode/0054.Spiral-Matrix/54. Spiral Matrix.go | package leetcode
// 解法 1
func spiralOrder(matrix [][]int) []int {
if len(matrix) == 0 {
return []int{}
}
res := []int{}
if len(matrix) == 1 {
for i := 0; i < len(matrix[0]); i++ {
res = append(res, matrix[0][i])
}
return res
}
if len(matrix[0]) == 1 {
for i := 0; i < len(matrix); i++ {
res = append(res, matrix[i][0])
}
return res
}
visit, m, n, round, x, y, spDir := make([][]int, len(matrix)), len(matrix), len(matrix[0]), 0, 0, 0, [][]int{
{0, 1}, // 朝右
{1, 0}, // 朝下
{0, -1}, // 朝左
{-1, 0}, // 朝上
}
for i := 0; i < m; i++ {
visit[i] = make([]int, n)
}
visit[x][y] = 1
res = append(res, matrix[x][y])
for i := 0; i < m*n; i++ {
x += spDir[round%4][0]
y += spDir[round%4][1]
if (x == 0 && y == n-1) || (x == m-1 && y == n-1) || (y == 0 && x == m-1) {
round++
}
if x > m-1 || y > n-1 || x < 0 || y < 0 {
return res
}
if visit[x][y] == 0 {
visit[x][y] = 1
res = append(res, matrix[x][y])
}
switch round % 4 {
case 0:
if y+1 <= n-1 && visit[x][y+1] == 1 {
round++
continue
}
case 1:
if x+1 <= m-1 && visit[x+1][y] == 1 {
round++
continue
}
case 2:
if y-1 >= 0 && visit[x][y-1] == 1 {
round++
continue
}
case 3:
if x-1 >= 0 && visit[x-1][y] == 1 {
round++
continue
}
}
}
return res
}
// 解法 2
func spiralOrder2(matrix [][]int) []int {
m := len(matrix)
if m == 0 {
return nil
}
n := len(matrix[0])
if n == 0 {
return nil
}
// top、left、right、bottom 分别是剩余区域的上、左、右、下的下标
top, left, bottom, right := 0, 0, m-1, n-1
count, sum := 0, m*n
res := []int{}
// 外层循环每次遍历一圈
for count < sum {
i, j := top, left
for j <= right && count < sum {
res = append(res, matrix[i][j])
count++
j++
}
i, j = top+1, right
for i <= bottom && count < sum {
res = append(res, matrix[i][j])
count++
i++
}
i, j = bottom, right-1
for j >= left && count < sum {
res = append(res, matrix[i][j])
count++
j--
}
i, j = bottom-1, left
for i > top && count < sum {
res = append(res, matrix[i][j])
count++
i--
}
// 进入到下一层
top, left, bottom, right = top+1, left+1, bottom-1, right-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/0299.Bulls-and-Cows/299.Bulls and Cows.go | leetcode/0299.Bulls-and-Cows/299.Bulls and Cows.go | package leetcode
import "strconv"
func getHint(secret string, guess string) string {
cntA, cntB := 0, 0
mpS := make(map[byte]int)
var strG []byte
n := len(secret)
var ans string
for i := 0; i < n; i++ {
if secret[i] == guess[i] {
cntA++
} else {
mpS[secret[i]] += 1
strG = append(strG, guess[i])
}
}
for _, v := range strG {
if _, ok := mpS[v]; ok {
if mpS[v] > 1 {
mpS[v] -= 1
} else {
delete(mpS, v)
}
cntB++
}
}
ans += strconv.Itoa(cntA) + "A" + strconv.Itoa(cntB) + "B"
return ans
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0299.Bulls-and-Cows/299.Bulls and Cows_test.go | leetcode/0299.Bulls-and-Cows/299.Bulls and Cows_test.go | package leetcode
import (
"fmt"
"testing"
)
type question299 struct {
para299
ans299
}
// para 是参数
type para299 struct {
secret string
guess string
}
// ans 是答案
type ans299 struct {
ans string
}
func Test_Problem299(t *testing.T) {
qs := []question299{
{
para299{"1807", "7810"},
ans299{"1A3B"},
},
{
para299{"1123", "0111"},
ans299{"1A1B"},
},
{
para299{"1", "0"},
ans299{"0A0B"},
},
{
para299{"1", "1"},
ans299{"1A0B"},
},
}
fmt.Printf("------------------------Leetcode Problem 299------------------------\n")
for _, q := range qs {
_, p := q.ans299, q.para299
fmt.Printf("【input】:%v 【output】:%v\n", p, getHint(p.secret, p.guess))
}
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/0047.Permutations-II/47. Permutations II_test.go | leetcode/0047.Permutations-II/47. Permutations II_test.go | package leetcode
import (
"fmt"
"testing"
)
type question47 struct {
para47
ans47
}
// para 是参数
// one 代表第一个参数
type para47 struct {
s []int
}
// ans 是答案
// one 代表第一个答案
type ans47 struct {
one [][]int
}
func Test_Problem47(t *testing.T) {
qs := []question47{
{
para47{[]int{1, 1, 2}},
ans47{[][]int{{1, 1, 2}, {1, 2, 1}, {2, 1, 1}}},
},
{
para47{[]int{1, 2, 2}},
ans47{[][]int{{1, 2, 2}, {2, 2, 1}, {2, 1, 2}}},
},
{
para47{[]int{2, 2, 2}},
ans47{[][]int{{2, 2, 2}}},
},
}
fmt.Printf("------------------------Leetcode Problem 47------------------------\n")
for _, q := range qs {
_, p := q.ans47, q.para47
fmt.Printf("【input】:%v 【output】:%v\n", p, permuteUnique(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/0047.Permutations-II/47. Permutations II.go | leetcode/0047.Permutations-II/47. Permutations II.go | package leetcode
import "sort"
func permuteUnique(nums []int) [][]int {
if len(nums) == 0 {
return [][]int{}
}
used, p, res := make([]bool, len(nums)), []int{}, [][]int{}
sort.Ints(nums) // 这里是去重的关键逻辑
generatePermutation47(nums, 0, p, &res, &used)
return res
}
func generatePermutation47(nums []int, index int, p []int, res *[][]int, used *[]bool) {
if index == len(nums) {
temp := make([]int, len(p))
copy(temp, p)
*res = append(*res, temp)
return
}
for i := 0; i < len(nums); i++ {
if !(*used)[i] {
if i > 0 && nums[i] == nums[i-1] && !(*used)[i-1] { // 这里是去重的关键逻辑
continue
}
(*used)[i] = true
p = append(p, nums[i])
generatePermutation47(nums, index+1, p, res, used)
p = p[:len(p)-1]
(*used)[i] = false
}
}
return
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1461.Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/1461. Check If a String Contains All Binary Codes of Size K_test.go | leetcode/1461.Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/1461. Check If a String Contains All Binary Codes of Size K_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1461 struct {
para1461
ans1461
}
// para 是参数
// one 代表第一个参数
type para1461 struct {
s string
k int
}
// ans 是答案
// one 代表第一个答案
type ans1461 struct {
one bool
}
func Test_Problem1461(t *testing.T) {
qs := []question1461{
{
para1461{"00110110", 2},
ans1461{true},
},
{
para1461{"00110", 2},
ans1461{true},
},
{
para1461{"0110", 1},
ans1461{true},
},
{
para1461{"0110", 2},
ans1461{false},
},
{
para1461{"0000000001011100", 4},
ans1461{false},
},
}
fmt.Printf("------------------------Leetcode Problem 1461------------------------\n")
for _, q := range qs {
_, p := q.ans1461, q.para1461
fmt.Printf("【input】:%v 【output】:%v\n", p, hasAllCodes(p.s, 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/1461.Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/1461. Check If a String Contains All Binary Codes of Size K.go | leetcode/1461.Check-If-a-String-Contains-All-Binary-Codes-of-Size-K/1461. Check If a String Contains All Binary Codes of Size K.go | package leetcode
import "math"
func hasAllCodes(s string, k int) bool {
need := int(math.Pow(2.0, float64(k)))
visited, mask, curr := make([]bool, need), (1<<k)-1, 0
for i := 0; i < len(s); i++ {
curr = ((curr << 1) | int(s[i]-'0')) & mask
if i >= k-1 { // mask 有效位达到了 k 位
if !visited[curr] {
need--
visited[curr] = true
if need == 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/0719.Find-K-th-Smallest-Pair-Distance/719. Find K-th Smallest Pair Distance_test.go | leetcode/0719.Find-K-th-Smallest-Pair-Distance/719. Find K-th Smallest Pair Distance_test.go | package leetcode
import (
"fmt"
"testing"
)
type question719 struct {
para719
ans719
}
// para 是参数
// one 代表第一个参数
type para719 struct {
num []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans719 struct {
one int
}
func Test_Problem719(t *testing.T) {
qs := []question719{
{
para719{[]int{1, 3, 1}, 1},
ans719{0},
},
{
para719{[]int{1, 1, 1}, 2},
ans719{0},
},
{
para719{[]int{1, 6, 1}, 3},
ans719{5},
},
{
para719{[]int{62, 100, 4}, 2},
ans719{58},
},
{
para719{[]int{9, 10, 7, 10, 6, 1, 5, 4, 9, 8}, 18},
ans719{2},
},
}
fmt.Printf("------------------------Leetcode Problem 719------------------------\n")
for _, q := range qs {
_, p := q.ans719, q.para719
fmt.Printf("【input】:%v 【output】:%v\n", p, smallestDistancePair(p.num, 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/0719.Find-K-th-Smallest-Pair-Distance/719. Find K-th Smallest Pair Distance.go | leetcode/0719.Find-K-th-Smallest-Pair-Distance/719. Find K-th Smallest Pair Distance.go | package leetcode
import (
"sort"
)
func smallestDistancePair(nums []int, k int) int {
sort.Ints(nums)
low, high := 0, nums[len(nums)-1]-nums[0]
for low < high {
mid := low + (high-low)>>1
tmp := findDistanceCount(nums, mid)
if tmp >= k {
high = mid
} else {
low = mid + 1
}
}
return low
}
// 解法一 双指针
func findDistanceCount(nums []int, num int) int {
count, i := 0, 0
for j := 1; j < len(nums); j++ {
for nums[j]-nums[i] > num && i < j {
i++
}
count += (j - i)
}
return count
}
// 解法二 暴力查找
func findDistanceCount1(nums []int, num int) int {
count := 0
for i := 0; i < len(nums); i++ {
for j := i + 1; j < len(nums); j++ {
if nums[j]-nums[i] <= num {
count++
}
}
}
return count
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/2022.Convert-1D-Array-Into-2D-Array/2022. Convert 1D Array Into 2D Array_test.go | leetcode/2022.Convert-1D-Array-Into-2D-Array/2022. Convert 1D Array Into 2D Array_test.go | package leetcode
import (
"fmt"
"testing"
)
type question2022 struct {
para2022
ans2022
}
// para 是参数
// one 代表第一个参数
type para2022 struct {
original []int
m int
n int
}
// ans 是答案
// one 代表第一个答案
type ans2022 struct {
one [][]int
}
func Test_Problem2022(t *testing.T) {
qs := []question2022{
{
para2022{[]int{1, 2, 3, 4}, 2, 2},
ans2022{[][]int{{1, 2}, {3, 4}}},
},
{
para2022{[]int{1, 2, 3}, 1, 3},
ans2022{[][]int{{1, 2, 3}}},
},
{
para2022{[]int{1, 2}, 1, 1},
ans2022{[][]int{{}}},
},
{
para2022{[]int{3}, 1, 2},
ans2022{[][]int{{3}}},
},
{
para2022{[]int{1, 1, 1, 1}, 4, 1},
ans2022{[][]int{{1, 1, 1, 1}}},
},
}
fmt.Printf("------------------------Leetcode Problem 2022------------------------\n")
for _, q := range qs {
_, p := q.ans2022, q.para2022
fmt.Printf("【input】:%v 【output】:%v\n", p, construct2DArray(p.original, p.m, 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/2022.Convert-1D-Array-Into-2D-Array/2022. Convert 1D Array Into 2D Array.go | leetcode/2022.Convert-1D-Array-Into-2D-Array/2022. Convert 1D Array Into 2D Array.go | package leetcode
func construct2DArray(original []int, m int, n int) [][]int {
if m*n != len(original) {
return [][]int{}
}
res := make([][]int, m)
for i := 0; i < m; i++ {
res[i] = original[n*i : n*(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/0145.Binary-Tree-Postorder-Traversal/145. Binary Tree Postorder Traversal.go | leetcode/0145.Binary-Tree-Postorder-Traversal/145. Binary Tree Postorder 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 postorderTraversal(root *TreeNode) []int {
var result []int
postorder(root, &result)
return result
}
func postorder(root *TreeNode, output *[]int) {
if root != nil {
postorder(root.Left, output)
postorder(root.Right, output)
*output = append(*output, root.Val)
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0145.Binary-Tree-Postorder-Traversal/145. Binary Tree Postorder Traversal_test.go | leetcode/0145.Binary-Tree-Postorder-Traversal/145. Binary Tree Postorder Traversal_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question145 struct {
para145
ans145
}
// para 是参数
// one 代表第一个参数
type para145 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans145 struct {
one []int
}
func Test_Problem145(t *testing.T) {
qs := []question145{
{
para145{[]int{}},
ans145{[]int{}},
},
{
para145{[]int{1}},
ans145{[]int{1}},
},
{
para145{[]int{1, structures.NULL, 2, 3}},
ans145{[]int{1, 2, 3}},
},
}
fmt.Printf("------------------------Leetcode Problem 145------------------------\n")
for _, q := range qs {
_, p := q.ans145, q.para145
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", postorderTraversal(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/1207.Unique-Number-of-Occurrences/1207. Unique Number of Occurrences_test.go | leetcode/1207.Unique-Number-of-Occurrences/1207. Unique Number of Occurrences_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1207 struct {
para1207
ans1207
}
// para 是参数
// one 代表第一个参数
type para1207 struct {
arr []int
}
// ans 是答案
// one 代表第一个答案
type ans1207 struct {
one bool
}
func Test_Problem1207(t *testing.T) {
qs := []question1207{
{
para1207{[]int{1, 2, 2, 1, 1, 3}},
ans1207{true},
},
{
para1207{[]int{1, 2}},
ans1207{false},
},
{
para1207{[]int{-3, 0, 1, -3, 1, 1, 1, -3, 10, 0}},
ans1207{true},
},
}
fmt.Printf("------------------------Leetcode Problem 1207------------------------\n")
for _, q := range qs {
_, p := q.ans1207, q.para1207
fmt.Printf("【input】:%v 【output】:%v\n", p, uniqueOccurrences(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/1207.Unique-Number-of-Occurrences/1207. Unique Number of Occurrences.go | leetcode/1207.Unique-Number-of-Occurrences/1207. Unique Number of Occurrences.go | package leetcode
func uniqueOccurrences(arr []int) bool {
freq, m := map[int]int{}, map[int]bool{}
for _, v := range arr {
freq[v]++
}
for _, v := range freq {
if _, ok := m[v]; !ok {
m[v] = true
} else {
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/1128.Number-of-Equivalent-Domino-Pairs/1128. Number of Equivalent Domino Pairs.go | leetcode/1128.Number-of-Equivalent-Domino-Pairs/1128. Number of Equivalent Domino Pairs.go | package leetcode
func numEquivDominoPairs(dominoes [][]int) int {
if dominoes == nil || len(dominoes) == 0 {
return 0
}
result, buckets := 0, [100]int{}
for _, dominoe := range dominoes {
key, rotatedKey := dominoe[0]*10+dominoe[1], dominoe[1]*10+dominoe[0]
if dominoe[0] != dominoe[1] {
if buckets[rotatedKey] > 0 {
result += buckets[rotatedKey]
}
}
if buckets[key] > 0 {
result += buckets[key]
buckets[key]++
} else {
buckets[key]++
}
}
return result
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1128.Number-of-Equivalent-Domino-Pairs/1128. Number of Equivalent Domino Pairs_test.go | leetcode/1128.Number-of-Equivalent-Domino-Pairs/1128. Number of Equivalent Domino Pairs_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1128 struct {
para1128
ans1128
}
// para 是参数
// one 代表第一个参数
type para1128 struct {
dominoes [][]int
}
// ans 是答案
// one 代表第一个答案
type ans1128 struct {
one int
}
func Test_Problem1128(t *testing.T) {
qs := []question1128{
{
para1128{[][]int{{1, 2}, {2, 1}, {3, 4}, {5, 6}}},
ans1128{1},
},
}
fmt.Printf("------------------------Leetcode Problem 1128------------------------\n")
for _, q := range qs {
_, p := q.ans1128, q.para1128
fmt.Printf("【input】:%v 【output】:%v\n", p, numEquivDominoPairs(p.dominoes))
}
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/1539.Kth-Missing-Positive-Number/1539. Kth Missing Positive Number_test.go | leetcode/1539.Kth-Missing-Positive-Number/1539. Kth Missing Positive Number_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1539 struct {
para1539
ans1539
}
// para 是参数
// one 代表第一个参数
type para1539 struct {
arr []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans1539 struct {
one int
}
func Test_Problem1539(t *testing.T) {
qs := []question1539{
{
para1539{[]int{2, 3, 4, 7, 11}, 5},
ans1539{9},
},
{
para1539{[]int{1, 2, 3, 4}, 2},
ans1539{6},
},
}
fmt.Printf("------------------------Leetcode Problem 1539------------------------\n")
for _, q := range qs {
_, p := q.ans1539, q.para1539
fmt.Printf("【input】:%v 【output】:%v \n", p, findKthPositive(p.arr, 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/1539.Kth-Missing-Positive-Number/1539. Kth Missing Positive Number.go | leetcode/1539.Kth-Missing-Positive-Number/1539. Kth Missing Positive Number.go | package leetcode
func findKthPositive(arr []int, k int) int {
positive, index := 1, 0
for index < len(arr) {
if arr[index] != positive {
k--
} else {
index++
}
if k == 0 {
break
}
positive++
}
if k != 0 {
positive += k - 1
}
return positive
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0106.Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/106. Construct Binary Tree from Inorder and Postorder Traversal_test.go | leetcode/0106.Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/106. Construct Binary Tree from Inorder and Postorder Traversal_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question106 struct {
para106
ans106
}
// para 是参数
// one 代表第一个参数
type para106 struct {
inorder []int
postorder []int
}
// ans 是答案
// one 代表第一个答案
type ans106 struct {
one []int
}
func Test_Problem106(t *testing.T) {
qs := []question106{
{
para106{[]int{9, 3, 15, 20, 7}, []int{9, 15, 7, 20, 3}},
ans106{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}},
},
}
fmt.Printf("------------------------Leetcode Problem 106------------------------\n")
for _, q := range qs {
_, p := q.ans106, q.para106
fmt.Printf("【input】:%v ", p)
fmt.Printf("【output】:%v \n", structures.Tree2ints(buildTree(p.inorder, p.postorder)))
}
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/0106.Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/106. Construct Binary Tree from Inorder and Postorder Traversal.go | leetcode/0106.Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/106. Construct Binary Tree from Inorder and Postorder 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
* }
*/
// 解法一, 直接传入需要的 slice 范围作为输入, 可以避免申请对应 inorder 索引的内存, 内存使用(leetcode test case) 4.7MB -> 4.3MB.
func buildTree(inorder []int, postorder []int) *TreeNode {
postorderLen := len(postorder)
if len(inorder) == 0 {
return nil
}
root := &TreeNode{Val: postorder[postorderLen-1]}
postorder = postorder[:postorderLen-1]
for pos, node := range inorder {
if node == root.Val {
root.Left = buildTree(inorder[:pos], postorder[:len(inorder[:pos])])
root.Right = buildTree(inorder[pos+1:], postorder[len(inorder[:pos]):])
}
}
return root
}
// 解法二
func buildTree1(inorder []int, postorder []int) *TreeNode {
inPos := make(map[int]int)
for i := 0; i < len(inorder); i++ {
inPos[inorder[i]] = i
}
return buildInPos2TreeDFS(postorder, 0, len(postorder)-1, 0, inPos)
}
func buildInPos2TreeDFS(post []int, postStart int, postEnd int, inStart int, inPos map[int]int) *TreeNode {
if postStart > postEnd {
return nil
}
root := &TreeNode{Val: post[postEnd]}
rootIdx := inPos[post[postEnd]]
leftLen := rootIdx - inStart
root.Left = buildInPos2TreeDFS(post, postStart, postStart+leftLen-1, inStart, inPos)
root.Right = buildInPos2TreeDFS(post, postStart+leftLen, postEnd-1, rootIdx+1, inPos)
return root
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0274.H-Index/274. H-Index.go | leetcode/0274.H-Index/274. H-Index.go | package leetcode
// 解法一
func hIndex(citations []int) int {
n := len(citations)
buckets := make([]int, n+1)
for _, c := range citations {
if c >= n {
buckets[n]++
} else {
buckets[c]++
}
}
count := 0
for i := n; i >= 0; i-- {
count += buckets[i]
if count >= i {
return i
}
}
return 0
}
// 解法二
func hIndex1(citations []int) int {
quickSort164(citations, 0, len(citations)-1)
hIndex := 0
for i := len(citations) - 1; i >= 0; i-- {
if citations[i] >= len(citations)-i {
hIndex++
} else {
break
}
}
return hIndex
}
func quickSort164(a []int, lo, hi int) {
if lo >= hi {
return
}
p := partition164(a, lo, hi)
quickSort164(a, lo, p-1)
quickSort164(a, p+1, hi)
}
func partition164(a []int, lo, hi int) int {
pivot := a[hi]
i := lo - 1
for j := lo; j < hi; j++ {
if a[j] < pivot {
i++
a[j], a[i] = a[i], a[j]
}
}
a[i+1], a[hi] = a[hi], a[i+1]
return i + 1
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0274.H-Index/274. H-Index_test.go | leetcode/0274.H-Index/274. H-Index_test.go | package leetcode
import (
"fmt"
"testing"
)
type question274 struct {
para274
ans274
}
// para 是参数
// one 代表第一个参数
type para274 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans274 struct {
one int
}
func Test_Problem274(t *testing.T) {
qs := []question274{
{
para274{[]int{3, 6, 9, 1}},
ans274{3},
},
{
para274{[]int{1}},
ans274{1},
},
{
para274{[]int{}},
ans274{0},
},
{
para274{[]int{3, 0, 6, 1, 5}},
ans274{3},
},
}
fmt.Printf("------------------------Leetcode Problem 274------------------------\n")
for _, q := range qs {
_, p := q.ans274, q.para274
fmt.Printf("【input】:%v 【output】:%v\n", p, hIndex(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/1716.Calculate-Money-in-Leetcode-Bank/1716. Calculate Money in Leetcode Bank_test.go | leetcode/1716.Calculate-Money-in-Leetcode-Bank/1716. Calculate Money in Leetcode Bank_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1716 struct {
para1716
ans1716
}
// para 是参数
// one 代表第一个参数
type para1716 struct {
n int
}
// ans 是答案
// one 代表第一个答案
type ans1716 struct {
one int
}
func Test_Problem1716(t *testing.T) {
qs := []question1716{
{
para1716{4},
ans1716{10},
},
{
para1716{10},
ans1716{37},
},
{
para1716{20},
ans1716{96},
},
}
fmt.Printf("------------------------Leetcode Problem 1716------------------------\n")
for _, q := range qs {
_, p := q.ans1716, q.para1716
fmt.Printf("【input】:%v 【output】:%v\n", p, totalMoney(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/1716.Calculate-Money-in-Leetcode-Bank/1716. Calculate Money in Leetcode Bank.go | leetcode/1716.Calculate-Money-in-Leetcode-Bank/1716. Calculate Money in Leetcode Bank.go | package leetcode
func totalMoney(n int) int {
res := 0
for tmp, count := 1, 7; n > 0; tmp, count = tmp+1, 7 {
for m := tmp; n > 0 && count > 0; m++ {
res += m
n--
count--
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0999.Available-Captures-for-Rook/999. Available Captures for Rook.go | leetcode/0999.Available-Captures-for-Rook/999. Available Captures for Rook.go | package leetcode
func numRookCaptures(board [][]byte) int {
num := 0
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[i]); j++ {
if board[i][j] == 'R' {
num += caputure(board, i-1, j, -1, 0) // Up
num += caputure(board, i+1, j, 1, 0) // Down
num += caputure(board, i, j-1, 0, -1) // Left
num += caputure(board, i, j+1, 0, 1) // Right
}
}
}
return num
}
func caputure(board [][]byte, x, y int, bx, by int) int {
for x >= 0 && x < len(board) && y >= 0 && y < len(board[x]) && board[x][y] != 'B' {
if board[x][y] == 'p' {
return 1
}
x += bx
y += by
}
return 0
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0999.Available-Captures-for-Rook/999. Available Captures for Rook_test.go | leetcode/0999.Available-Captures-for-Rook/999. Available Captures for Rook_test.go | package leetcode
import (
"fmt"
"testing"
)
type question999 struct {
para999
ans999
}
// para 是参数
// one 代表第一个参数
type para999 struct {
one [][]byte
}
// ans 是答案
// one 代表第一个答案
type ans999 struct {
one int
}
func Test_Problem999(t *testing.T) {
qs := []question999{
{
para999{[][]byte{
{'.', '.', '.', '.', '.', '.', '.', '.'},
{'.', 'p', 'p', 'p', 'p', 'p', '.', '.'},
{'.', 'p', 'p', 'B', 'p', 'p', '.', '.'},
{'.', 'p', 'B', 'R', 'B', 'p', '.', '.'},
{'.', 'p', 'p', 'B', 'p', 'p', '.', '.'},
{'.', 'p', 'p', 'p', 'p', 'p', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.'},
}},
ans999{0},
},
{
para999{[][]byte{
{'.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', 'p', '.', '.', '.', '.'},
{'.', '.', '.', 'R', '.', '.', '.', 'p'},
{'.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', 'p', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.'},
}},
ans999{3},
},
{
para999{[][]byte{
{'.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', 'p', '.', '.', '.', '.'},
{'.', '.', '.', 'p', '.', '.', '.', '.'},
{'p', 'p', '.', 'R', '.', 'p', 'B', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', 'B', '.', '.', '.', '.'},
{'.', '.', '.', 'p', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.'},
}},
ans999{3},
},
}
fmt.Printf("------------------------Leetcode Problem 999------------------------\n")
for _, q := range qs {
_, p := q.ans999, q.para999
fmt.Printf("【input】:%v 【output】:%v\n", p, numRookCaptures(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/0387.First-Unique-Character-in-a-String/387. First Unique Character in a String.go | leetcode/0387.First-Unique-Character-in-a-String/387. First Unique Character in a String.go | package leetcode
// 解法一
func firstUniqChar(s string) int {
result := make([]int, 26)
for i := 0; i < len(s); i++ {
result[s[i]-'a']++
}
for i := 0; i < len(s); i++ {
if result[s[i]-'a'] == 1 {
return i
}
}
return -1
}
// 解法二
// 执行用时: 8 ms
// 内存消耗: 5.2 MB
func firstUniqChar1(s string) int {
charMap := make([][2]int, 26)
for i := 0; i < 26; i++ {
charMap[i][0] = -1
charMap[i][1] = -1
}
for i := 0; i < len(s); i++ {
if charMap[s[i]-'a'][0] == -1 {
charMap[s[i]-'a'][0] = i
} else { //已经出现过
charMap[s[i]-'a'][1] = i
}
}
res := len(s)
for i := 0; i < 26; i++ {
//只出现了一次
if charMap[i][0] >= 0 && charMap[i][1] == -1 {
if charMap[i][0] < res {
res = charMap[i][0]
}
}
}
if res == len(s) {
return -1
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0387.First-Unique-Character-in-a-String/387. First Unique Character in a String_test.go | leetcode/0387.First-Unique-Character-in-a-String/387. First Unique Character in a String_test.go | package leetcode
import (
"fmt"
"testing"
)
type question387 struct {
para387
ans387
}
// para 是参数
// one 代表第一个参数
type para387 struct {
n string
}
// ans 是答案
// one 代表第一个答案
type ans387 struct {
one int
}
func Test_Problem387(t *testing.T) {
qs := []question387{
{
para387{"leetcode"},
ans387{0},
},
{
para387{"loveleetcode"},
ans387{2},
},
}
fmt.Printf("------------------------Leetcode Problem 387------------------------\n")
for _, q := range qs {
_, p := q.ans387, q.para387
fmt.Printf("【input】:%v 【output】:%v\n", p, firstUniqChar(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/1268.Search-Suggestions-System/1268. Search Suggestions System.go | leetcode/1268.Search-Suggestions-System/1268. Search Suggestions System.go | package leetcode
import (
"sort"
)
func suggestedProducts(products []string, searchWord string) [][]string {
sort.Strings(products)
searchWordBytes, result := []byte(searchWord), make([][]string, 0, len(searchWord))
for i := 1; i <= len(searchWord); i++ {
searchWordBytes[i-1]++
products = products[:sort.SearchStrings(products, string(searchWordBytes[:i]))]
searchWordBytes[i-1]--
products = products[sort.SearchStrings(products, searchWord[:i]):]
if len(products) > 3 {
result = append(result, products[:3])
} else {
result = append(result, products)
}
}
return result
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1268.Search-Suggestions-System/1268. Search Suggestions System_test.go | leetcode/1268.Search-Suggestions-System/1268. Search Suggestions System_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1268 struct {
para1268
ans1268
}
// para 是参数
// one 代表第一个参数
type para1268 struct {
products []string
searchWord string
}
// ans 是答案
// one 代表第一个答案
type ans1268 struct {
one [][]string
}
func Test_Problem1268(t *testing.T) {
qs := []question1268{
{
para1268{[]string{"bags", "baggage", "banner", "box", "cloths"}, "bags"},
ans1268{[][]string{
{"baggage", "bags", "banner"}, {"baggage", "bags", "banner"}, {"baggage", "bags"}, {"bags"},
}},
},
{
para1268{[]string{"mobile", "mouse", "moneypot", "monitor", "mousepad"}, "mouse"},
ans1268{[][]string{
{"mobile", "moneypot", "monitor"},
{"mobile", "moneypot", "monitor"},
{"mouse", "mousepad"},
{"mouse", "mousepad"},
{"mouse", "mousepad"},
}},
},
{
para1268{[]string{"havana"}, "havana"},
ans1268{[][]string{
{"havana"}, {"havana"}, {"havana"}, {"havana"}, {"havana"}, {"havana"},
}},
},
{
para1268{[]string{"havana"}, "tatiana"},
ans1268{[][]string{
{}, {}, {}, {}, {}, {}, {},
}},
},
}
fmt.Printf("------------------------Leetcode Problem 1268------------------------\n")
for _, q := range qs {
_, p := q.ans1268, q.para1268
fmt.Printf("【input】:%v 【output】:%v\n", p, suggestedProducts(p.products, p.searchWord))
}
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/0748.Shortest-Completing-Word/748. Shortest Completing Word.go | leetcode/0748.Shortest-Completing-Word/748. Shortest Completing Word.go | package leetcode
import "unicode"
func shortestCompletingWord(licensePlate string, words []string) string {
lp := genCnter(licensePlate)
var ret string
for _, w := range words {
if match(lp, w) {
if len(w) < len(ret) || ret == "" {
ret = w
}
}
}
return ret
}
func genCnter(lp string) [26]int {
cnter := [26]int{}
for _, ch := range lp {
if unicode.IsLetter(ch) {
cnter[unicode.ToLower(ch)-'a']++
}
}
return cnter
}
func match(lp [26]int, w string) bool {
m := [26]int{}
for _, ch := range w {
m[ch-'a']++
}
for k, v := range lp {
if m[k] < v {
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/0748.Shortest-Completing-Word/748. Shortest Completing Word_test.go | leetcode/0748.Shortest-Completing-Word/748. Shortest Completing Word_test.go | package leetcode
import (
"fmt"
"testing"
)
type question748 struct {
para748
ans748
}
// para 是参数
// one 代表第一个参数
type para748 struct {
c string
w []string
}
// ans 是答案
// one 代表第一个答案
type ans748 struct {
one string
}
func Test_Problem748(t *testing.T) {
qs := []question748{
{
para748{"1s3 PSt", []string{"step", "steps", "stripe", "stepple"}},
ans748{"steps"},
},
{
para748{"1s3 456", []string{"looks", "pest", "stew", "show"}},
ans748{"pest"},
},
}
fmt.Printf("------------------------Leetcode Problem 748------------------------\n")
for _, q := range qs {
_, p := q.ans748, q.para748
fmt.Printf("【input】:%v 【output】:%v\n", p, shortestCompletingWord(p.c, 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/0872.Leaf-Similar-Trees/872. Leaf-Similar Trees.go | leetcode/0872.Leaf-Similar-Trees/872. Leaf-Similar Trees.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 leafSimilar(root1 *TreeNode, root2 *TreeNode) bool {
leaf1, leaf2 := []int{}, []int{}
dfsLeaf(root1, &leaf1)
dfsLeaf(root2, &leaf2)
if len(leaf1) != len(leaf2) {
return false
}
for i := range leaf1 {
if leaf1[i] != leaf2[i] {
return false
}
}
return true
}
func dfsLeaf(root *TreeNode, leaf *[]int) {
if root != nil {
if root.Left == nil && root.Right == nil {
*leaf = append(*leaf, root.Val)
}
dfsLeaf(root.Left, leaf)
dfsLeaf(root.Right, leaf)
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0872.Leaf-Similar-Trees/872. Leaf-Similar Trees_test.go | leetcode/0872.Leaf-Similar-Trees/872. Leaf-Similar Trees_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question872 struct {
para872
ans872
}
// para 是参数
// one 代表第一个参数
type para872 struct {
one []int
two []int
}
// ans 是答案
// one 代表第一个答案
type ans872 struct {
one bool
}
func Test_Problem872(t *testing.T) {
qs := []question872{
{
para872{[]int{-10, -3, 0, 5, 9}, []int{-10, -3, 0, 5, 9}},
ans872{true},
},
}
fmt.Printf("------------------------Leetcode Problem 872------------------------\n")
for _, q := range qs {
_, p := q.ans872, q.para872
tree1 := structures.Ints2TreeNode(p.one)
tree2 := structures.Ints2TreeNode(p.two)
fmt.Printf("【input】:%v 【output】:%v\n", p, leafSimilar(tree1, tree2))
}
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/1710.Maximum-Units-on-a-Truck/1710. Maximum Units on a Truck_test.go | leetcode/1710.Maximum-Units-on-a-Truck/1710. Maximum Units on a Truck_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1710 struct {
para1710
ans1710
}
// para 是参数
// one 代表第一个参数
type para1710 struct {
boxTypes [][]int
truckSize int
}
// ans 是答案
// one 代表第一个答案
type ans1710 struct {
one int
}
func Test_Problem1710(t *testing.T) {
qs := []question1710{
{
para1710{[][]int{{1, 3}, {2, 2}, {3, 1}}, 4},
ans1710{8},
},
{
para1710{[][]int{{5, 10}, {2, 5}, {4, 7}, {3, 9}}, 10},
ans1710{91},
},
}
fmt.Printf("------------------------Leetcode Problem 1710------------------------\n")
for _, q := range qs {
_, p := q.ans1710, q.para1710
fmt.Printf("【input】:%v 【output】:%v\n", p, maximumUnits(p.boxTypes, p.truckSize))
}
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/1710.Maximum-Units-on-a-Truck/1710. Maximum Units on a Truck.go | leetcode/1710.Maximum-Units-on-a-Truck/1710. Maximum Units on a Truck.go | package leetcode
import "sort"
func maximumUnits(boxTypes [][]int, truckSize int) int {
sort.Slice(boxTypes, func(i, j int) bool {
return boxTypes[i][1] > boxTypes[j][1]
})
res := 0
for i := 0; truckSize > 0 && i < len(boxTypes); i++ {
if truckSize >= boxTypes[i][0] {
truckSize -= boxTypes[i][0]
res += (boxTypes[i][1] * boxTypes[i][0])
} else {
res += (truckSize * boxTypes[i][1])
truckSize = 0
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1221.Split-a-String-in-Balanced-Strings/1221. Split a String in Balanced Strings.go | leetcode/1221.Split-a-String-in-Balanced-Strings/1221. Split a String in Balanced Strings.go | package leetcode
func balancedStringSplit(s string) int {
count, res := 0, 0
for _, r := range s {
if r == 'R' {
count++
} else {
count--
}
if count == 0 {
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/1221.Split-a-String-in-Balanced-Strings/1221. Split a String in Balanced Strings_test.go | leetcode/1221.Split-a-String-in-Balanced-Strings/1221. Split a String in Balanced Strings_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1221 struct {
para1221
ans1221
}
// para 是参数
// one 代表第一个参数
type para1221 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans1221 struct {
one int
}
func Test_Problem1221(t *testing.T) {
qs := []question1221{
{
para1221{"RLRRLLRLRL"},
ans1221{4},
},
{
para1221{"RLLLLRRRLR"},
ans1221{3},
},
{
para1221{"LLLLRRRR"},
ans1221{1},
},
}
fmt.Printf("------------------------Leetcode Problem 1221------------------------\n")
for _, q := range qs {
_, p := q.ans1221, q.para1221
fmt.Printf("【input】:%v 【output】:%v\n", p, balancedStringSplit(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/0172.Factorial-Trailing-Zeroes/172. Factorial Trailing Zeroes_test.go | leetcode/0172.Factorial-Trailing-Zeroes/172. Factorial Trailing Zeroes_test.go | package leetcode
import (
"fmt"
"testing"
)
type question172 struct {
para172
ans172
}
// para 是参数
// one 代表第一个参数
type para172 struct {
s int
}
// ans 是答案
// one 代表第一个答案
type ans172 struct {
one int
}
func Test_Problem172(t *testing.T) {
qs := []question172{
{
para172{3},
ans172{0},
},
{
para172{5},
ans172{1},
},
}
fmt.Printf("------------------------Leetcode Problem 172------------------------\n")
for _, q := range qs {
_, p := q.ans172, q.para172
fmt.Printf("【input】:%v 【output】:%v\n", p, trailingZeroes(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/0172.Factorial-Trailing-Zeroes/172. Factorial Trailing Zeroes.go | leetcode/0172.Factorial-Trailing-Zeroes/172. Factorial Trailing Zeroes.go | package leetcode
func trailingZeroes(n int) int {
if n/5 == 0 {
return 0
}
return n/5 + trailingZeroes(n/5)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0928.Minimize-Malware-Spread-II/928. Minimize Malware Spread II.go | leetcode/0928.Minimize-Malware-Spread-II/928. Minimize Malware Spread II.go | package leetcode
import (
"math"
"github.com/halfrost/LeetCode-Go/template"
)
func minMalwareSpread2(graph [][]int, initial []int) int {
if len(initial) == 0 {
return 0
}
uf, minIndex, count, countMap, malwareMap, infectMap := template.UnionFind{}, initial[0], math.MinInt64, map[int]int{}, map[int]int{}, map[int]map[int]int{}
for _, v := range initial {
malwareMap[v]++
}
uf.Init(len(graph))
for i := range graph {
for j := range graph[i] {
if i == j {
break
}
if graph[i][j] == 1 && malwareMap[i] == 0 && malwareMap[j] == 0 {
uf.Union(i, j)
}
}
}
for i := 0; i < len(graph); i++ {
countMap[uf.Find(i)]++
}
// 记录每个集合和直接相邻病毒节点的个数
for _, i := range initial {
for j := 0; j < len(graph); j++ {
if malwareMap[j] == 0 && graph[i][j] == 1 {
p := uf.Find(j)
if _, ok := infectMap[p]; ok {
infectMap[p][i] = i
} else {
tmp := map[int]int{}
tmp[i] = i
infectMap[p] = tmp
}
}
}
}
// 选出病毒节点中序号最小的
for _, v := range initial {
minIndex = min(minIndex, v)
}
for i, v := range infectMap {
// 找出只和一个病毒节点相连通的
if len(v) == 1 {
tmp := countMap[uf.Find(i)]
keys := []int{}
for k := range v {
keys = append(keys, k)
}
if count == tmp && minIndex > keys[0] {
minIndex = keys[0]
}
if count < tmp {
minIndex = keys[0]
count = tmp
}
}
}
return minIndex
}
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/0928.Minimize-Malware-Spread-II/928. Minimize Malware Spread II_test.go | leetcode/0928.Minimize-Malware-Spread-II/928. Minimize Malware Spread II_test.go | package leetcode
import (
"fmt"
"testing"
)
type question928 struct {
para928
ans928
}
// para 是参数
// one 代表第一个参数
type para928 struct {
graph [][]int
initial []int
}
// ans 是答案
// one 代表第一个答案
type ans928 struct {
one int
}
func Test_Problem928(t *testing.T) {
qs := []question928{
{
para928{[][]int{{1, 0, 0, 0}, {0, 1, 1, 1}, {0, 1, 1, 0}, {0, 1, 0, 1}}, []int{1, 3}},
ans928{1},
},
{
para928{[][]int{{1, 1, 1, 0}, {1, 1, 0, 0}, {1, 0, 1, 0}, {0, 0, 0, 1}}, []int{3, 2}},
ans928{2},
},
{
para928{[][]int{{1, 1, 0}, {1, 1, 1}, {0, 1, 1}}, []int{0, 1}},
ans928{1},
},
{
para928{[][]int{{1, 1, 0}, {1, 1, 0}, {0, 0, 1}}, []int{0, 1}},
ans928{0},
},
{
para928{[][]int{{1, 1, 0, 0}, {1, 1, 1, 0}, {0, 1, 1, 1}, {0, 0, 1, 1}}, []int{0, 1}},
ans928{1},
},
{
para928{[][]int{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 1}, {0, 0, 1, 1}}, []int{3, 1}},
ans928{3},
},
{
para928{[][]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}},
ans928{0},
},
}
fmt.Printf("------------------------Leetcode Problem 928------------------------\n")
for _, q := range qs {
_, p := q.ans928, q.para928
fmt.Printf("【input】:%v 【output】:%v\n", p, minMalwareSpread2(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/0082.Remove-Duplicates-from-Sorted-List-II/82. Remove Duplicates from Sorted List II.go | leetcode/0082.Remove-Duplicates-from-Sorted-List-II/82. Remove Duplicates from Sorted List II.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 deleteDuplicates1(head *ListNode) *ListNode {
if head == nil {
return nil
}
if head.Next == nil {
return head
}
newHead := &ListNode{Next: head, Val: -999999}
cur := newHead
last := newHead
front := head
for front.Next != nil {
if front.Val == cur.Val {
// fmt.Printf("相同节点front = %v | cur = %v | last = %v\n", front.Val, cur.Val, last.Val)
front = front.Next
continue
} else {
if cur.Next != front {
// fmt.Printf("删除重复节点front = %v | cur = %v | last = %v\n", front.Val, cur.Val, last.Val)
last.Next = front
if front.Next != nil && front.Next.Val != front.Val {
last = front
}
cur = front
front = front.Next
} else {
// fmt.Printf("常规循环前front = %v | cur = %v | last = %v\n", front.Val, cur.Val, last.Val)
last = cur
cur = cur.Next
front = front.Next
// fmt.Printf("常规循环后front = %v | cur = %v | last = %v\n", front.Val, cur.Val, last.Val)
}
}
}
if front.Val == cur.Val {
// fmt.Printf("相同节点front = %v | cur = %v | last = %v\n", front.Val, cur.Val, last.Val)
last.Next = nil
} else {
if cur.Next != front {
last.Next = front
}
}
return newHead.Next
}
func deleteDuplicates2(head *ListNode) *ListNode {
if head == nil {
return nil
}
if head.Next != nil && head.Val == head.Next.Val {
for head.Next != nil && head.Val == head.Next.Val {
head = head.Next
}
return deleteDuplicates(head.Next)
}
head.Next = deleteDuplicates(head.Next)
return head
}
func deleteDuplicates(head *ListNode) *ListNode {
cur := head
if head == nil {
return nil
}
if head.Next == nil {
return head
}
for cur.Next != nil {
if cur.Next.Val == cur.Val {
cur.Next = cur.Next.Next
} else {
cur = cur.Next
}
}
return head
}
// 双循环简单解法 O(n*m)
func deleteDuplicates3(head *ListNode) *ListNode {
if head == nil {
return head
}
nilNode := &ListNode{Val: 0, Next: head}
head = nilNode
lastVal := 0
for head.Next != nil && head.Next.Next != nil {
if head.Next.Val == head.Next.Next.Val {
lastVal = head.Next.Val
for head.Next != nil && lastVal == head.Next.Val {
head.Next = head.Next.Next
}
} else {
head = head.Next
}
}
return nilNode.Next
}
// 双指针+删除标志位,单循环解法 O(n)
func deleteDuplicates4(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
nilNode := &ListNode{Val: 0, Next: head}
// 上次遍历有删除操作的标志位
lastIsDel := false
// 虚拟空结点
head = nilNode
// 前后指针用于判断
pre, back := head.Next, head.Next.Next
// 每次只删除前面的一个重复的元素,留一个用于下次遍历判重
// pre, back 指针的更新位置和值比较重要和巧妙
for head.Next != nil && head.Next.Next != nil {
if pre.Val != back.Val && lastIsDel {
head.Next = head.Next.Next
pre, back = head.Next, head.Next.Next
lastIsDel = false
continue
}
if pre.Val == back.Val {
head.Next = head.Next.Next
pre, back = head.Next, head.Next.Next
lastIsDel = true
} else {
head = head.Next
pre, back = head.Next, head.Next.Next
lastIsDel = false
}
}
// 处理 [1,1] 这种删除还剩一个的情况
if lastIsDel && head.Next != nil {
head.Next = nil
}
return nilNode.Next
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0082.Remove-Duplicates-from-Sorted-List-II/82. Remove Duplicates from Sorted List II_test.go | leetcode/0082.Remove-Duplicates-from-Sorted-List-II/82. Remove Duplicates from Sorted List II_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question82 struct {
para82
ans82
}
// para 是参数
// one 代表第一个参数
type para82 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans82 struct {
one []int
}
func Test_Problem82(t *testing.T) {
qs := []question82{
{
para82{[]int{1, 1, 2, 2, 3, 4, 4, 4}},
ans82{[]int{3}},
},
{
para82{[]int{1, 1, 1, 1, 1, 1}},
ans82{[]int{}},
},
{
para82{[]int{1, 1, 1, 2, 3}},
ans82{[]int{2, 3}},
},
{
para82{[]int{1}},
ans82{[]int{1}},
},
{
para82{[]int{}},
ans82{[]int{}},
},
{
para82{[]int{1, 2, 2, 2, 2}},
ans82{[]int{1}},
},
{
para82{[]int{1, 1, 2, 3, 3, 4, 5, 5, 6}},
ans82{[]int{2, 4, 6}},
},
{
para82{[]int{1, 1, 2, 3, 3, 4, 5, 6}},
ans82{[]int{2, 4, 5, 6}},
},
{
para82{[]int{0, 1, 2, 2, 3, 4}},
ans82{[]int{0, 1, 2, 2, 3, 4}},
},
}
fmt.Printf("------------------------Leetcode Problem 82------------------------\n")
for _, q := range qs {
_, p := q.ans82, q.para82
fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(deleteDuplicates1(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/2165.Smallest-Value-of-the-Rearranged-Number/2165. Smallest Value of the Rearranged Number.go | leetcode/2165.Smallest-Value-of-the-Rearranged-Number/2165. Smallest Value of the Rearranged Number.go | package leetcode
import "sort"
func smallestNumber(num int64) int64 {
pos := true
if num < 0 {
pos = false
num *= -1
}
nums, m, res := []int{}, map[int]int{}, 0
for num != 0 {
tmp := int(num % 10)
m[tmp]++
num = num / 10
}
for k := range m {
nums = append(nums, k)
}
if pos {
sort.Ints(nums)
} else {
sort.Sort(sort.Reverse(sort.IntSlice(nums)))
}
if nums[0] == 0 && len(nums) > 1 {
res += nums[1]
m[nums[1]]--
}
for _, v := range nums {
if res != 0 {
for j := m[v]; j > 0; j-- {
res = res * 10
res += v
}
} else {
res += v
tmp := m[v] - 1
for j := tmp; j > 0; j-- {
res = res * 10
res += v
}
}
}
if !pos {
return -1 * int64(res)
}
return int64(res)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/2165.Smallest-Value-of-the-Rearranged-Number/2165. Smallest Value of the Rearranged Number_test.go | leetcode/2165.Smallest-Value-of-the-Rearranged-Number/2165. Smallest Value of the Rearranged Number_test.go | package leetcode
import (
"fmt"
"testing"
)
type question2165 struct {
para2165
ans2165
}
// para 是参数
// one 代表第一个参数
type para2165 struct {
nums int64
}
// ans 是答案
// one 代表第一个答案
type ans2165 struct {
one int64
}
func Test_Problem1(t *testing.T) {
qs := []question2165{
{
para2165{310},
ans2165{103},
},
{
para2165{5059},
ans2165{5059},
},
{
para2165{-7605},
ans2165{-7650},
},
}
fmt.Printf("------------------------Leetcode Problem 2165------------------------\n")
for _, q := range qs {
_, p := q.ans2165, q.para2165
fmt.Printf("【input】:%v 【output】:%v\n", p, smallestNumber(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/0094.Binary-Tree-Inorder-Traversal/94. Binary Tree Inorder Traversal_test.go | leetcode/0094.Binary-Tree-Inorder-Traversal/94. Binary Tree Inorder Traversal_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question94 struct {
para94
ans94
}
// para 是参数
// one 代表第一个参数
type para94 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans94 struct {
one []int
}
func Test_Problem94(t *testing.T) {
qs := []question94{
{
para94{[]int{}},
ans94{[]int{}},
},
{
para94{[]int{1}},
ans94{[]int{1}},
},
{
para94{[]int{1, structures.NULL, 2, 3}},
ans94{[]int{1, 2, 3}},
},
}
fmt.Printf("------------------------Leetcode Problem 94------------------------\n")
for _, q := range qs {
_, p := q.ans94, q.para94
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", inorderTraversal(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/0094.Binary-Tree-Inorder-Traversal/94. Binary Tree Inorder Traversal.go | leetcode/0094.Binary-Tree-Inorder-Traversal/94. Binary Tree Inorder 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 inorderTraversal(root *TreeNode) []int {
var result []int
inorder(root, &result)
return result
}
func inorder(root *TreeNode, output *[]int) {
if root != nil {
inorder(root.Left, output)
*output = append(*output, root.Val)
inorder(root.Right, output)
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0070.Climbing-Stairs/70. Climbing Stairs_test.go | leetcode/0070.Climbing-Stairs/70. Climbing Stairs_test.go | package leetcode
import (
"fmt"
"testing"
)
type question70 struct {
para70
ans70
}
// para 是参数
// one 代表第一个参数
type para70 struct {
n int
}
// ans 是答案
// one 代表第一个答案
type ans70 struct {
one int
}
func Test_Problem70(t *testing.T) {
qs := []question70{
{
para70{2},
ans70{2},
},
{
para70{3},
ans70{3},
},
}
fmt.Printf("------------------------Leetcode Problem 70------------------------\n")
for _, q := range qs {
_, p := q.ans70, q.para70
fmt.Printf("【input】:%v 【output】:%v\n", p, climbStairs(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/0070.Climbing-Stairs/70. Climbing Stairs.go | leetcode/0070.Climbing-Stairs/70. Climbing Stairs.go | package leetcode
func climbStairs(n int) int {
dp := make([]int, n+1)
dp[0], dp[1] = 1, 1
for i := 2; i <= n; i++ {
dp[i] = dp[i-1] + dp[i-2]
}
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/0476.Number-Complement/476. Number Complement.go | leetcode/0476.Number-Complement/476. Number Complement.go | package leetcode
// 解法一
func findComplement(num int) int {
xx := ^0 // ^0 = 1111111111111111111111
for xx&num > 0 {
xx <<= 1 // 构造出来的 xx = 1111111…000000,0 的个数就是 num 的长度
}
return ^xx ^ num // xx ^ num,结果是前面的 0 全是 1 的num,再取反即是答案
}
// 解法二
func findComplement1(num int) int {
temp := 1
for temp <= num {
temp <<= 1 // 构造出来的 temp = 00000……10000,末尾 0 的个数是 num 的长度
}
return (temp - 1) ^ num // temp - 1 即是前面都是 0,num 长度的末尾都是 1 的数,再异或 num 即是最终结果
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0476.Number-Complement/476. Number Complement_test.go | leetcode/0476.Number-Complement/476. Number Complement_test.go | package leetcode
import (
"fmt"
"testing"
)
type question476 struct {
para476
ans476
}
// para 是参数
// one 代表第一个参数
type para476 struct {
one int
}
// ans 是答案
// one 代表第一个答案
type ans476 struct {
one int
}
func Test_Problem476(t *testing.T) {
qs := []question476{
{
para476{5},
ans476{2},
},
{
para476{1},
ans476{0},
},
}
fmt.Printf("------------------------Leetcode Problem 476------------------------\n")
for _, q := range qs {
_, p := q.ans476, q.para476
fmt.Printf("【input】:%v 【output】:%v\n", p, findComplement(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/0383.Ransom-Note/383.Ransom Note_test.go | leetcode/0383.Ransom-Note/383.Ransom Note_test.go | package leetcode
import (
"fmt"
"testing"
)
type question383 struct {
para383
ans383
}
// para 是参数
type para383 struct {
ransomNote string
magazine string
}
// ans 是答案
type ans383 struct {
ans bool
}
func Test_Problem383(t *testing.T) {
qs := []question383{
{
para383{"a", "b"},
ans383{false},
},
{
para383{"aa", "ab"},
ans383{false},
},
{
para383{"aa", "aab"},
ans383{true},
},
}
fmt.Printf("------------------------Leetcode Problem 383------------------------\n")
for _, q := range qs {
_, p := q.ans383, q.para383
fmt.Printf("【input】:%v 【output】:%v\n", p, canConstruct(p.ransomNote, p.magazine))
}
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/0383.Ransom-Note/383.Ransom Note.go | leetcode/0383.Ransom-Note/383.Ransom Note.go | package leetcode
func canConstruct(ransomNote string, magazine string) bool {
if len(ransomNote) > len(magazine) {
return false
}
var cnt [26]int
for _, v := range magazine {
cnt[v-'a']++
}
for _, v := range ransomNote {
cnt[v-'a']--
if cnt[v-'a'] < 0 {
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/0856.Score-of-Parentheses/856. Score of Parentheses_test.go | leetcode/0856.Score-of-Parentheses/856. Score of Parentheses_test.go | package leetcode
import (
"fmt"
"testing"
)
type question856 struct {
para856
ans856
}
// para 是参数
// one 代表第一个参数
type para856 struct {
one string
}
// ans 是答案
// one 代表第一个答案
type ans856 struct {
one int
}
func Test_Problem856(t *testing.T) {
qs := []question856{
{
para856{"()"},
ans856{1},
},
{
para856{"(())"},
ans856{2},
},
{
para856{"()()"},
ans856{2},
},
{
para856{"(()(()))"},
ans856{6},
},
{
para856{"()(())"},
ans856{3},
},
{
para856{"((()()))"},
ans856{8},
},
}
fmt.Printf("------------------------Leetcode Problem 856------------------------\n")
for _, q := range qs {
_, p := q.ans856, q.para856
fmt.Printf("【input】:%v 【output】:%v\n", p, scoreOfParentheses(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/0856.Score-of-Parentheses/856. Score of Parentheses.go | leetcode/0856.Score-of-Parentheses/856. Score of Parentheses.go | package leetcode
func scoreOfParentheses(S string) int {
res, stack, top, temp := 0, []int{}, -1, 0
for _, s := range S {
if s == '(' {
stack = append(stack, -1)
top++
} else {
temp = 0
for stack[top] != -1 {
temp += stack[top]
stack = stack[:len(stack)-1]
top--
}
stack = stack[:len(stack)-1]
top--
if temp == 0 {
stack = append(stack, 1)
top++
} else {
stack = append(stack, temp*2)
top++
}
}
}
for len(stack) != 0 {
res += stack[top]
stack = stack[:len(stack)-1]
top--
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0460.LFU-Cache/460. LFU Cache_test.go | leetcode/0460.LFU-Cache/460. LFU Cache_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem460(t *testing.T) {
obj := Constructor(5)
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
obj.Put(1, 1)
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
obj.Put(2, 2)
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
obj.Put(3, 3)
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
obj.Put(4, 4)
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
obj.Put(5, 5)
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
param1 := obj.Get(4)
fmt.Printf("param_1 = %v obj.list = %v obj.map = %v obj.min = %v\n", param1, MLists2Ints(&obj), MList2Ints(&obj), obj.min)
param1 = obj.Get(4)
fmt.Printf("param_1 = %v obj.list = %v obj.map = %v obj.min = %v\n", param1, MLists2Ints(&obj), MList2Ints(&obj), obj.min)
param1 = obj.Get(4)
fmt.Printf("param_1 = %v obj.list = %v obj.map = %v obj.min = %v\n", param1, MLists2Ints(&obj), MList2Ints(&obj), obj.min)
param1 = obj.Get(5)
fmt.Printf("param_1 = %v obj.list = %v obj.map = %v obj.min = %v\n", param1, MLists2Ints(&obj), MList2Ints(&obj), obj.min)
param1 = obj.Get(5)
fmt.Printf("param_1 = %v obj.list = %v obj.map = %v obj.min = %v\n", param1, MLists2Ints(&obj), MList2Ints(&obj), obj.min)
param1 = obj.Get(5)
fmt.Printf("param_1 = %v obj.list = %v obj.map = %v obj.min = %v\n", param1, MLists2Ints(&obj), MList2Ints(&obj), obj.min)
obj.Put(6, 6)
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
obj.Put(7, 7)
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
obj.Put(8, 8)
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
}
func MList2Ints(lfu *LFUCache) map[int][][]int {
res := map[int][][]int{}
for k, v := range lfu.nodes {
node := v.Value.(*node)
arr := [][]int{}
tmp := []int{node.key, node.value, node.frequency}
arr = append(arr, tmp)
res[k] = arr
}
return res
}
func MLists2Ints(lfu *LFUCache) map[int][]int {
res := map[int][]int{}
for k, v := range lfu.lists {
tmp := []int{}
for head := v.Front(); head != nil; head = head.Next() {
tmp = append(tmp, head.Value.(*node).value)
}
res[k] = tmp
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0460.LFU-Cache/460. LFU Cache.go | leetcode/0460.LFU-Cache/460. LFU Cache.go | package leetcode
import "container/list"
type LFUCache struct {
nodes map[int]*list.Element
lists map[int]*list.List
capacity int
min int
}
type node struct {
key int
value int
frequency int
}
func Constructor(capacity int) LFUCache {
return LFUCache{nodes: make(map[int]*list.Element),
lists: make(map[int]*list.List),
capacity: capacity,
min: 0,
}
}
func (this *LFUCache) Get(key int) int {
value, ok := this.nodes[key]
if !ok {
return -1
}
currentNode := value.Value.(*node)
this.lists[currentNode.frequency].Remove(value)
currentNode.frequency++
if _, ok := this.lists[currentNode.frequency]; !ok {
this.lists[currentNode.frequency] = list.New()
}
newList := this.lists[currentNode.frequency]
newNode := newList.PushBack(currentNode)
this.nodes[key] = newNode
if currentNode.frequency-1 == this.min && this.lists[currentNode.frequency-1].Len() == 0 {
this.min++
}
return currentNode.value
}
func (this *LFUCache) Put(key int, value int) {
if this.capacity == 0 {
return
}
if currentValue, ok := this.nodes[key]; ok {
currentNode := currentValue.Value.(*node)
currentNode.value = value
this.Get(key)
return
}
if this.capacity == len(this.nodes) {
currentList := this.lists[this.min]
frontNode := currentList.Front()
delete(this.nodes, frontNode.Value.(*node).key)
currentList.Remove(frontNode)
}
this.min = 1
currentNode := &node{
key: key,
value: value,
frequency: 1,
}
if _, ok := this.lists[1]; !ok {
this.lists[1] = list.New()
}
newList := this.lists[1]
newNode := newList.PushBack(currentNode)
this.nodes[key] = newNode
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0859.Buddy-Strings/859.Buddy Strings_test.go | leetcode/0859.Buddy-Strings/859.Buddy Strings_test.go | package leetcode
import (
"fmt"
"testing"
)
type question859 struct {
para859
ans859
}
// para 是参数
type para859 struct {
s string
goal string
}
// ans 是答案
type ans859 struct {
ans bool
}
func Test_Problem859(t *testing.T) {
qs := []question859{
{
para859{"ab", "ba"},
ans859{true},
},
{
para859{"ab", "ab"},
ans859{false},
},
{
para859{"aa", "aa"},
ans859{true},
},
{
para859{"aaaaaaabc", "aaaaaaacb"},
ans859{true},
},
}
fmt.Printf("------------------------Leetcode Problem 859------------------------\n")
for _, q := range qs {
_, p := q.ans859, q.para859
fmt.Printf("【input】:%v 【output】:%v\n", p, buddyStrings(p.s, p.goal))
}
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/0859.Buddy-Strings/859.Buddy Strings.go | leetcode/0859.Buddy-Strings/859.Buddy Strings.go | package leetcode
func buddyStrings(s string, goal string) bool {
if len(s) != len(goal) || len(s) <= 1 {
return false
}
mp := make(map[byte]int)
if s == goal {
for i := 0; i < len(s); i++ {
if _, ok := mp[s[i]]; ok {
return true
}
mp[s[i]]++
}
return false
}
first, second := -1, -1
for i := 0; i < len(s); i++ {
if s[i] != goal[i] {
if first == -1 {
first = i
} else if second == -1 {
second = i
} else {
return false
}
}
}
return second != -1 && s[first] == goal[second] && s[second] == goal[first]
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0976.Largest-Perimeter-Triangle/976. Largest Perimeter Triangle.go | leetcode/0976.Largest-Perimeter-Triangle/976. Largest Perimeter Triangle.go | package leetcode
func largestPerimeter(A []int) int {
if len(A) < 3 {
return 0
}
quickSort164(A, 0, len(A)-1)
for i := len(A) - 1; i >= 2; i-- {
if (A[i]+A[i-1] > A[i-2]) && (A[i]+A[i-2] > A[i-1]) && (A[i-2]+A[i-1] > A[i]) {
return A[i] + A[i-1] + A[i-2]
}
}
return 0
}
func quickSort164(a []int, lo, hi int) {
if lo >= hi {
return
}
p := partition164(a, lo, hi)
quickSort164(a, lo, p-1)
quickSort164(a, p+1, hi)
}
func partition164(a []int, lo, hi int) int {
pivot := a[hi]
i := lo - 1
for j := lo; j < hi; j++ {
if a[j] < pivot {
i++
a[j], a[i] = a[i], a[j]
}
}
a[i+1], a[hi] = a[hi], a[i+1]
return i + 1
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0976.Largest-Perimeter-Triangle/976. Largest Perimeter Triangle_test.go | leetcode/0976.Largest-Perimeter-Triangle/976. Largest Perimeter Triangle_test.go | package leetcode
import (
"fmt"
"testing"
)
type question976 struct {
para976
ans976
}
// para 是参数
// one 代表第一个参数
type para976 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans976 struct {
one int
}
func Test_Problem976(t *testing.T) {
qs := []question976{
{
para976{[]int{1, 2}},
ans976{0},
},
{
para976{[]int{1, 2, 3}},
ans976{0},
},
{
para976{[]int{}},
ans976{0},
},
{
para976{[]int{2, 1, 2}},
ans976{5},
},
{
para976{[]int{1, 1, 2}},
ans976{0},
},
{
para976{[]int{3, 2, 3, 4}},
ans976{10},
},
{
para976{[]int{3, 6, 2, 3}},
ans976{8},
},
}
fmt.Printf("------------------------Leetcode Problem 976------------------------\n")
for _, q := range qs {
_, p := q.ans976, q.para976
fmt.Printf("【input】:%v 【output】:%v\n", p, largestPerimeter(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/0836.Rectangle-Overlap/836. Rectangle Overlap.go | leetcode/0836.Rectangle-Overlap/836. Rectangle Overlap.go | package leetcode
func isRectangleOverlap(rec1 []int, rec2 []int) bool {
return rec1[0] < rec2[2] && rec2[0] < rec1[2] && rec1[1] < rec2[3] && rec2[1] < rec1[3]
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0836.Rectangle-Overlap/836. Rectangle Overlap_test.go | leetcode/0836.Rectangle-Overlap/836. Rectangle Overlap_test.go | package leetcode
import (
"fmt"
"testing"
)
type question836 struct {
para836
ans836
}
// para 是参数
// one 代表第一个参数
type para836 struct {
rec1 []int
rec2 []int
}
// ans 是答案
// one 代表第一个答案
type ans836 struct {
one bool
}
func Test_Problem836(t *testing.T) {
qs := []question836{
{
para836{[]int{0, 0, 2, 2}, []int{1, 1, 3, 3}},
ans836{true},
},
{
para836{[]int{0, 0, 1, 1}, []int{1, 0, 2, 1}},
ans836{false},
},
}
fmt.Printf("------------------------Leetcode Problem 836------------------------\n")
for _, q := range qs {
_, p := q.ans836, q.para836
fmt.Printf("【input】:%v 【output】:%v\n", p, isRectangleOverlap(p.rec1, p.rec2))
}
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/0794.Valid-Tic-Tac-Toe-State/794.Valid Tic-Tac-Toe State_test.go | leetcode/0794.Valid-Tic-Tac-Toe-State/794.Valid Tic-Tac-Toe State_test.go | package leetcode
import (
"fmt"
"testing"
)
type question794 struct {
para794
ans794
}
// para 是参数
type para794 struct {
board []string
}
// ans 是答案
type ans794 struct {
ans bool
}
func Test_Problem794(t *testing.T) {
qs := []question794{
{
para794{[]string{"O ", " ", " "}},
ans794{false},
},
{
para794{[]string{"XOX", " X ", " "}},
ans794{false},
},
{
para794{[]string{"XXX", " ", "OOO"}},
ans794{false},
},
{
para794{[]string{"XOX", "O O", "XOX"}},
ans794{true},
},
}
fmt.Printf("------------------------Leetcode Problem 794------------------------\n")
for _, q := range qs {
_, p := q.ans794, q.para794
fmt.Printf("【input】:%v 【output】:%v\n", p.board, validTicTacToe(p.board))
}
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/0794.Valid-Tic-Tac-Toe-State/794.Valid Tic-Tac-Toe State.go | leetcode/0794.Valid-Tic-Tac-Toe-State/794.Valid Tic-Tac-Toe State.go | package leetcode
func validTicTacToe(board []string) bool {
cntX, cntO := 0, 0
for i := range board {
for j := range board[i] {
if board[i][j] == 'X' {
cntX++
} else if board[i][j] == 'O' {
cntO++
}
}
}
if cntX < cntO || cntX > cntO+1 {
return false
}
if cntX == cntO {
return process(board, 'X')
}
return process(board, 'O')
}
func process(board []string, c byte) bool {
//某一行是"ccc"
if board[0] == string([]byte{c, c, c}) || board[1] == string([]byte{c, c, c}) || board[2] == string([]byte{c, c, c}) {
return false
}
//某一列是"ccc"
if (board[0][0] == c && board[1][0] == c && board[2][0] == c) ||
(board[0][1] == c && board[1][1] == c && board[2][1] == c) ||
(board[0][2] == c && board[1][2] == c && board[2][2] == c) {
return false
}
//某一对角线是"ccc"
if (board[0][0] == c && board[1][1] == c && board[2][2] == c) ||
(board[0][2] == c && board[1][1] == c && board[2][0] == c) {
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/2181.Merge-Nodes-in-Between-Zeros/2181. Merge Nodes in Between Zeros_test.go | leetcode/2181.Merge-Nodes-in-Between-Zeros/2181. Merge Nodes in Between Zeros_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question2181 struct {
para2181
ans2181
}
// para 是参数
// one 代表第一个参数
type para2181 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans2181 struct {
one []int
}
func Test_Problem2181(t *testing.T) {
qs := []question2181{
{
para2181{[]int{0, 3, 1, 0, 4, 5, 2, 0}},
ans2181{[]int{4, 11}},
},
{
para2181{[]int{0, 1, 0, 3, 0, 2, 2, 0}},
ans2181{[]int{1, 3, 4}},
},
}
fmt.Printf("------------------------Leetcode Problem 2181------------------------\n")
for _, q := range qs {
_, p := q.ans2181, q.para2181
fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(mergeNodes(structures.Ints2List(p.one))))
}
fmt.Printf("\n\n\n")
}
func removeElements(head *ListNode, val int) *ListNode {
if head == nil {
return head
}
newHead := &ListNode{Val: 0, Next: head}
pre := newHead
cur := head
for cur != nil {
if cur.Val == val {
pre.Next = cur.Next
} else {
pre = cur
}
cur = cur.Next
}
return newHead.Next
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/2181.Merge-Nodes-in-Between-Zeros/2181. Merge Nodes in Between Zeros.go | leetcode/2181.Merge-Nodes-in-Between-Zeros/2181. Merge Nodes in Between Zeros.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 mergeNodes(head *ListNode) *ListNode {
res := &ListNode{}
h := res
if head.Next == nil {
return &structures.ListNode{}
}
cur := head
sum := 0
for cur.Next != nil {
if cur.Next.Val != 0 {
sum += cur.Next.Val
} else {
h.Next = &ListNode{Val: sum, Next: nil}
h = h.Next
sum = 0
}
cur = cur.Next
}
return res.Next
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0519.Random-Flip-Matrix/519.Random Flip Matrix_test.go | leetcode/0519.Random-Flip-Matrix/519.Random Flip Matrix_test.go | package leetcode
import (
"fmt"
"testing"
)
type question519 struct {
para519
ans519
}
// para 是参数
type para519 struct {
para []string
val [][]int
}
// ans 是答案
type ans519 struct {
ans [][]int
}
func Test_Problem519(t *testing.T) {
qs := []question519{
{
para519{[]string{"Solution", "flip", "flip", "flip", "reset", "flip"}, [][]int{{3, 1}, {}, {}, {}, {}, {}}},
ans519{[][]int{nil, {1, 0}, {2, 0}, {0, 0}, nil, {2, 0}}},
},
}
fmt.Printf("------------------------Leetcode Problem 519------------------------\n")
for _, q := range qs {
_, p := q.ans519, q.para519
sol := Constructor(0, 0)
for _, v := range p.para {
if v == "Solution" {
sol = Constructor(q.val[0][0], q.val[0][1])
fmt.Printf("【input】:%v 【output】:%v\n", v, nil)
} else if v == "flip" {
fmt.Printf("【input】:%v 【output】:%v\n", v, sol.Flip())
} else {
sol.Reset()
fmt.Printf("【input】:%v 【output】:%v\n", v, nil)
}
}
}
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/0519.Random-Flip-Matrix/519.Random Flip Matrix.go | leetcode/0519.Random-Flip-Matrix/519.Random Flip Matrix.go | package leetcode
import (
"math/rand"
)
type Solution struct {
r int
c int
total int
mp map[int]int
}
func Constructor(m int, n int) Solution {
return Solution{
r: m,
c: n,
total: m * n,
mp: map[int]int{},
}
}
func (this *Solution) Flip() []int {
k := rand.Intn(this.total)
val := k
if v, ok := this.mp[k]; ok {
val = v
}
if _, ok := this.mp[this.total-1]; ok {
this.mp[k] = this.mp[this.total-1]
} else {
this.mp[k] = this.total - 1
}
delete(this.mp, this.total-1)
this.total--
newR, newC := val/this.c, val%this.c
return []int{newR, newC}
}
func (this *Solution) Reset() {
this.total = this.r * this.c
this.mp = map[int]int{}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0888.Fair-Candy-Swap/888. Fair Candy Swap_test.go | leetcode/0888.Fair-Candy-Swap/888. Fair Candy Swap_test.go | package leetcode
import (
"fmt"
"testing"
)
type question888 struct {
para888
ans888
}
// para 是参数
// one 代表第一个参数
type para888 struct {
one []int
two []int
}
// ans 是答案
// one 代表第一个答案
type ans888 struct {
one []int
}
func Test_Problem888(t *testing.T) {
qs := []question888{
{
para888{[]int{}, []int{}},
ans888{[]int{}},
},
{
para888{[]int{1, 1}, []int{2, 2}},
ans888{[]int{1, 2}},
},
{
para888{[]int{1, 2}, []int{2, 3}},
ans888{[]int{1, 2}},
},
{
para888{[]int{2}, []int{1, 3}},
ans888{[]int{2, 3}},
},
{
para888{[]int{1, 2, 5}, []int{2, 4}},
ans888{[]int{5, 4}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 888------------------------\n")
for _, q := range qs {
_, p := q.ans888, q.para888
fmt.Printf("【input】:%v 【output】:%v\n", p, fairCandySwap(p.one, p.two))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0888.Fair-Candy-Swap/888. Fair Candy Swap.go | leetcode/0888.Fair-Candy-Swap/888. Fair Candy Swap.go | package leetcode
func fairCandySwap(A []int, B []int) []int {
hDiff, aMap := diff(A, B)/2, make(map[int]int, len(A))
for _, a := range A {
aMap[a] = a
}
for _, b := range B {
if a, ok := aMap[hDiff+b]; ok {
return []int{a, b}
}
}
return nil
}
func diff(A []int, B []int) int {
diff, maxLen := 0, max(len(A), len(B))
for i := 0; i < maxLen; i++ {
if i < len(A) {
diff += A[i]
}
if i < len(B) {
diff -= B[i]
}
}
return diff
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0386.Lexicographical-Numbers/386. Lexicographical Numbers.go | leetcode/0386.Lexicographical-Numbers/386. Lexicographical Numbers.go | package leetcode
func lexicalOrder(n int) []int {
res := make([]int, 0, n)
dfs386(1, n, &res)
return res
}
func dfs386(x, n int, res *[]int) {
limit := (x + 10) / 10 * 10
for x <= n && x < limit {
*res = append(*res, x)
if x*10 <= n {
dfs386(x*10, n, res)
}
x++
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0386.Lexicographical-Numbers/386. Lexicographical Numbers_test.go | leetcode/0386.Lexicographical-Numbers/386. Lexicographical Numbers_test.go | package leetcode
import (
"fmt"
"testing"
)
type question386 struct {
para386
ans386
}
// para 是参数
// one 代表第一个参数
type para386 struct {
n int
}
// ans 是答案
// one 代表第一个答案
type ans386 struct {
one []int
}
func Test_Problem386(t *testing.T) {
qs := []question386{
{
para386{13},
ans386{[]int{1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9}},
},
}
fmt.Printf("------------------------Leetcode Problem 386------------------------\n")
for _, q := range qs {
_, p := q.ans386, q.para386
fmt.Printf("【input】:%v 【output】:%v\n", p, lexicalOrder(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/0151.Reverse-Words-in-a-String/151. Reverse Words in a String.go | leetcode/0151.Reverse-Words-in-a-String/151. Reverse Words in a String.go | package leetcode
import "strings"
func reverseWords151(s string) string {
ss := strings.Fields(s)
reverse151(&ss, 0, len(ss)-1)
return strings.Join(ss, " ")
}
func reverse151(m *[]string, i int, j int) {
for i <= j {
(*m)[i], (*m)[j] = (*m)[j], (*m)[i]
i++
j--
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0151.Reverse-Words-in-a-String/151. Reverse Words in a String_test.go | leetcode/0151.Reverse-Words-in-a-String/151. Reverse Words in a String_test.go | package leetcode
import (
"fmt"
"testing"
)
type question151 struct {
para151
ans151
}
// para 是参数
// one 代表第一个参数
type para151 struct {
one string
}
// ans 是答案
// one 代表第一个答案
type ans151 struct {
one string
}
func Test_Problem151(t *testing.T) {
qs := []question151{
{
para151{"the sky is blue"},
ans151{"blue is sky the"},
},
{
para151{" hello world! "},
ans151{"world! hello"},
},
{
para151{"a good example"},
ans151{"example good a"},
},
}
fmt.Printf("------------------------Leetcode Problem 151------------------------\n")
for _, q := range qs {
_, p := q.ans151, q.para151
fmt.Printf("【input】:%v 【output】:%v\n", p, reverseWords151(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/0547.Number-of-Provinces/547. Number of Provinces_test.go | leetcode/0547.Number-of-Provinces/547. Number of Provinces_test.go | package leetcode
import (
"fmt"
"testing"
)
type question547 struct {
para547
ans547
}
// para 是参数
// one 代表第一个参数
type para547 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans547 struct {
one int
}
func Test_Problem547(t *testing.T) {
qs := []question547{
{
para547{[][]int{{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}},
ans547{3},
},
{
para547{[][]int{{1, 1, 0}, {1, 1, 0}, {0, 0, 1}}},
ans547{2},
},
{
para547{[][]int{{1, 1, 0}, {1, 1, 1}, {0, 1, 1}}},
ans547{1},
},
}
fmt.Printf("------------------------Leetcode Problem 547------------------------\n")
for _, q := range qs {
_, p := q.ans547, q.para547
fmt.Printf("【input】:%v 【output】:%v\n", p, findCircleNum(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/0547.Number-of-Provinces/547. Number of Provinces.go | leetcode/0547.Number-of-Provinces/547. Number of Provinces.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/template"
)
// 解法一 并查集
func findCircleNum(M [][]int) int {
n := len(M)
if n == 0 {
return 0
}
uf := template.UnionFind{}
uf.Init(n)
for i := 0; i < n; i++ {
for j := 0; j <= i; j++ {
if M[i][j] == 1 {
uf.Union(i, j)
}
}
}
return uf.TotalCount()
}
// 解法二 FloodFill DFS 暴力解法
func findCircleNum1(M [][]int) int {
if len(M) == 0 {
return 0
}
visited := make([]bool, len(M))
res := 0
for i := range M {
if !visited[i] {
dfs547(M, i, visited)
res++
}
}
return res
}
func dfs547(M [][]int, cur int, visited []bool) {
visited[cur] = true
for j := 0; j < len(M[cur]); j++ {
if !visited[j] && M[cur][j] == 1 {
dfs547(M, j, visited)
}
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1254.Number-of-Closed-Islands/1254. Number of Closed Islands_test.go | leetcode/1254.Number-of-Closed-Islands/1254. Number of Closed Islands_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1254 struct {
para1254
ans1254
}
// para 是参数
// one 代表第一个参数
type para1254 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans1254 struct {
one int
}
func Test_Problem1254(t *testing.T) {
qs := []question1254{
{
para1254{[][]int{
{1, 1, 1, 1, 0},
{1, 1, 0, 1, 0},
{1, 1, 0, 0, 0},
{0, 0, 0, 0, 0},
}},
ans1254{0},
},
{
para1254{[][]int{
{1, 1, 0, 0, 0},
{1, 1, 0, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 1, 1},
}},
ans1254{0},
},
{
para1254{[][]int{
{1, 1, 1, 1, 1, 1, 1, 0},
{1, 0, 0, 0, 0, 1, 1, 0},
{1, 0, 1, 0, 1, 1, 1, 0},
{1, 0, 0, 0, 0, 1, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 0},
}},
ans1254{2},
},
{
para1254{[][]int{
{0, 0, 1, 0, 0},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
}},
ans1254{1},
},
{
para1254{[][]int{
{1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 1, 1, 0, 1},
{1, 0, 1, 0, 1, 0, 1},
{1, 0, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1},
}},
ans1254{2},
},
}
fmt.Printf("------------------------Leetcode Problem 1254------------------------\n")
for _, q := range qs {
_, p := q.ans1254, q.para1254
fmt.Printf("【input】:%v 【output】:%v\n", p, closedIsland(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/1254.Number-of-Closed-Islands/1254. Number of Closed Islands.go | leetcode/1254.Number-of-Closed-Islands/1254. Number of Closed Islands.go | package leetcode
var dir = [][]int{
{-1, 0},
{0, 1},
{1, 0},
{0, -1},
}
func closedIsland(grid [][]int) int {
m := len(grid)
if m == 0 {
return 0
}
n := len(grid[0])
if n == 0 {
return 0
}
res, visited := 0, make([][]bool, m)
for i := 0; i < m; i++ {
visited[i] = make([]bool, n)
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
isEdge := false
if grid[i][j] == 0 && !visited[i][j] {
checkIslands(grid, &visited, i, j, &isEdge)
if !isEdge {
res++
}
}
}
}
return res
}
func checkIslands(grid [][]int, visited *[][]bool, x, y int, isEdge *bool) {
if (x == 0 || x == len(grid)-1 || y == 0 || y == len(grid[0])-1) && grid[x][y] == 0 {
*isEdge = true
}
(*visited)[x][y] = true
for i := 0; i < 4; i++ {
nx := x + dir[i][0]
ny := y + dir[i][1]
if isIntInBoard(grid, nx, ny) && !(*visited)[nx][ny] && grid[nx][ny] == 0 {
checkIslands(grid, visited, nx, ny, isEdge)
}
}
*isEdge = *isEdge || false
}
func isIntInBoard(board [][]int, x, y int) bool {
return x >= 0 && x < len(board) && y >= 0 && y < len(board[0])
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0506.Relative-Ranks/506.Relative Ranks_test.go | leetcode/0506.Relative-Ranks/506.Relative Ranks_test.go | package leetcode
import (
"fmt"
"testing"
)
type question506 struct {
para506
ans506
}
// para 是参数
type para506 struct {
score []int
}
// ans 是答案
type ans506 struct {
ans []string
}
func Test_Problem506(t *testing.T) {
qs := []question506{
{
para506{[]int{5, 4, 3, 2, 1}},
ans506{[]string{"Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"}},
},
{
para506{[]int{10, 3, 8, 9, 4}},
ans506{[]string{"Gold Medal", "5", "Bronze Medal", "Silver Medal", "4"}},
},
}
fmt.Printf("------------------------Leetcode Problem 506------------------------\n")
for _, q := range qs {
_, p := q.ans506, q.para506
fmt.Printf("【input】:%v 【output】:%v\n", p.score, findRelativeRanks(p.score))
}
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/0506.Relative-Ranks/506.Relative Ranks.go | leetcode/0506.Relative-Ranks/506.Relative Ranks.go | package leetcode
import (
"sort"
"strconv"
)
func findRelativeRanks(score []int) []string {
mp := make(map[int]int)
for i, v := range score {
mp[v] = i
}
sort.Slice(score, func(i, j int) bool {
return score[i] > score[j]
})
ans := make([]string, len(score))
for i, v := range score {
if i == 0 {
ans[mp[v]] = "Gold Medal"
} else if i == 1 {
ans[mp[v]] = "Silver Medal"
} else if i == 2 {
ans[mp[v]] = "Bronze Medal"
} else {
ans[mp[v]] = strconv.Itoa(i + 1)
}
}
return ans
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0851.Loud-and-Rich/851. Loud and Rich.go | leetcode/0851.Loud-and-Rich/851. Loud and Rich.go | package leetcode
func loudAndRich(richer [][]int, quiet []int) []int {
edges := make([][]int, len(quiet))
for i := range edges {
edges[i] = []int{}
}
indegrees := make([]int, len(quiet))
for _, edge := range richer {
n1, n2 := edge[0], edge[1]
edges[n1] = append(edges[n1], n2)
indegrees[n2]++
}
res := make([]int, len(quiet))
for i := range res {
res[i] = i
}
queue := []int{}
for i, v := range indegrees {
if v == 0 {
queue = append(queue, i)
}
}
for len(queue) > 0 {
nexts := []int{}
for _, n1 := range queue {
for _, n2 := range edges[n1] {
indegrees[n2]--
if quiet[res[n2]] > quiet[res[n1]] {
res[n2] = res[n1]
}
if indegrees[n2] == 0 {
nexts = append(nexts, n2)
}
}
}
queue = nexts
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0851.Loud-and-Rich/851. Loud and Rich_test.go | leetcode/0851.Loud-and-Rich/851. Loud and Rich_test.go | package leetcode
import (
"fmt"
"testing"
)
type question851 struct {
para851
ans851
}
// para 是参数
// one 代表第一个参数
type para851 struct {
richer [][]int
quiet []int
}
// ans 是答案
// one 代表第一个答案
type ans851 struct {
one []int
}
func Test_Problem851(t *testing.T) {
qs := []question851{
{
para851{[][]int{{1, 0}, {2, 1}, {3, 1}, {3, 7}, {4, 3}, {5, 3}}, []int{3, 2, 5, 4, 6, 1, 7, 0}},
ans851{[]int{5, 5, 2, 5, 4, 5, 6, 7}},
},
}
fmt.Printf("------------------------Leetcode Problem 851------------------------\n")
for _, q := range qs {
_, p := q.ans851, q.para851
fmt.Printf("【input】:%v 【output】:%v\n", p, loudAndRich(p.richer, p.quiet))
}
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/0033.Search-in-Rotated-Sorted-Array/33. Search in Rotated Sorted Array_test.go | leetcode/0033.Search-in-Rotated-Sorted-Array/33. Search in Rotated Sorted Array_test.go | package leetcode
import (
"fmt"
"testing"
)
type question33 struct {
para33
ans33
}
// para 是参数
// one 代表第一个参数
type para33 struct {
nums []int
target int
}
// ans 是答案
// one 代表第一个答案
type ans33 struct {
one int
}
func Test_Problem33(t *testing.T) {
qs := []question33{
{
para33{[]int{3, 1}, 1},
ans33{1},
},
{
para33{[]int{4, 5, 6, 7, 0, 1, 2}, 0},
ans33{4},
},
{
para33{[]int{4, 5, 6, 7, 0, 1, 2}, 3},
ans33{-1},
},
}
fmt.Printf("------------------------Leetcode Problem 33------------------------\n")
for _, q := range qs {
_, p := q.ans33, q.para33
fmt.Printf("【input】:%v 【output】:%v\n", p, search33(p.nums, 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/0033.Search-in-Rotated-Sorted-Array/33. Search in Rotated Sorted Array.go | leetcode/0033.Search-in-Rotated-Sorted-Array/33. Search in Rotated Sorted Array.go | package leetcode
func search33(nums []int, target int) int {
if len(nums) == 0 {
return -1
}
low, high := 0, len(nums)-1
for low <= high {
mid := low + (high-low)>>1
if nums[mid] == target {
return mid
} else if nums[mid] > nums[low] { // 在数值大的一部分区间里
if nums[low] <= target && target < nums[mid] {
high = mid - 1
} else {
low = mid + 1
}
} else if nums[mid] < nums[high] { // 在数值小的一部分区间里
if nums[mid] < target && target <= nums[high] {
low = mid + 1
} else {
high = mid - 1
}
} else {
if nums[low] == nums[mid] {
low++
}
if nums[high] == nums[mid] {
high--
}
}
}
return -1
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0024.Swap-Nodes-in-Pairs/24. Swap Nodes in Pairs_test.go | leetcode/0024.Swap-Nodes-in-Pairs/24. Swap Nodes in Pairs_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question24 struct {
para24
ans24
}
// para 是参数
// one 代表第一个参数
type para24 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans24 struct {
one []int
}
func Test_Problem24(t *testing.T) {
qs := []question24{
{
para24{[]int{}},
ans24{[]int{}},
},
{
para24{[]int{1}},
ans24{[]int{1}},
},
{
para24{[]int{1, 2, 3, 4}},
ans24{[]int{2, 1, 4, 3}},
},
{
para24{[]int{1, 2, 3, 4, 5}},
ans24{[]int{2, 1, 4, 3, 5}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 24------------------------\n")
for _, q := range qs {
_, p := q.ans24, q.para24
fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(swapPairs(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/0024.Swap-Nodes-in-Pairs/24. Swap Nodes in Pairs.go | leetcode/0024.Swap-Nodes-in-Pairs/24. Swap Nodes in Pairs.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 swapPairs(head *ListNode) *ListNode {
dummy := &ListNode{Next: head}
for pt := dummy; pt != nil && pt.Next != nil && pt.Next.Next != nil; {
pt, pt.Next, pt.Next.Next, pt.Next.Next.Next = pt.Next, pt.Next.Next, pt.Next.Next.Next, pt.Next
}
return dummy.Next
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0198.House-Robber/198. House Robber.go | leetcode/0198.House-Robber/198. House Robber.go | package leetcode
// 解法一 DP
func rob198(nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
if n == 1 {
return nums[0]
}
// dp[i] 代表抢 nums[0...i] 房子的最大价值
dp := make([]int, n)
dp[0], dp[1] = nums[0], max(nums[1], nums[0])
for i := 2; i < n; i++ {
dp[i] = max(dp[i-1], nums[i]+dp[i-2])
}
return dp[n-1]
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
// 解法二 DP 优化辅助空间,把迭代的值保存在 2 个变量中
func rob198_1(nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
curMax, preMax := 0, 0
for i := 0; i < n; i++ {
tmp := curMax
curMax = max(curMax, nums[i]+preMax)
preMax = tmp
}
return curMax
}
// 解法三 模拟
func rob(nums []int) int {
// a 对于偶数位上的最大值的记录
// b 对于奇数位上的最大值的记录
a, b := 0, 0
for i := 0; i < len(nums); i++ {
if i%2 == 0 {
a = max(a+nums[i], b)
} else {
b = max(a, b+nums[i])
}
}
return max(a, b)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0198.House-Robber/198. House Robber_test.go | leetcode/0198.House-Robber/198. House Robber_test.go | package leetcode
import (
"fmt"
"testing"
)
type question198 struct {
para198
ans198
}
// para 是参数
// one 代表第一个参数
type para198 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans198 struct {
one int
}
func Test_Problem198(t *testing.T) {
qs := []question198{
{
para198{[]int{1, 2}},
ans198{2},
},
{
para198{[]int{1, 2, 3, 1}},
ans198{4},
},
{
para198{[]int{2, 7, 9, 3, 1}},
ans198{12},
},
}
fmt.Printf("------------------------Leetcode Problem 198------------------------\n")
for _, q := range qs {
_, p := q.ans198, q.para198
fmt.Printf("【input】:%v 【output】:%v\n", p, rob198(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/1313.Decompress-Run-Length-Encoded-List/1313. Decompress Run-Length Encoded List.go | leetcode/1313.Decompress-Run-Length-Encoded-List/1313. Decompress Run-Length Encoded List.go | package leetcode
func decompressRLElist(nums []int) []int {
res := []int{}
for i := 0; i < len(nums); i += 2 {
for j := 0; j < nums[i]; j++ {
res = append(res, nums[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/1313.Decompress-Run-Length-Encoded-List/1313. Decompress Run-Length Encoded List_test.go | leetcode/1313.Decompress-Run-Length-Encoded-List/1313. Decompress Run-Length Encoded List_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1313 struct {
para1313
ans1313
}
// para 是参数
// one 代表第一个参数
type para1313 struct {
nums []int
}
// ans 是答案
// one 代表第一个答案
type ans1313 struct {
one []int
}
func Test_Problem1313(t *testing.T) {
qs := []question1313{
{
para1313{[]int{1, 2, 3, 4}},
ans1313{[]int{2, 4, 4, 4}},
},
{
para1313{[]int{1, 1, 2, 3}},
ans1313{[]int{1, 3, 3}},
},
{
para1313{[]int{}},
ans1313{[]int{}},
},
}
fmt.Printf("------------------------Leetcode Problem 1313------------------------\n")
for _, q := range qs {
_, p := q.ans1313, q.para1313
fmt.Printf("【input】:%v ", p)
fmt.Printf("【output】:%v \n", decompressRLElist(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/0120.Triangle/120. Triangle.go | leetcode/0120.Triangle/120. Triangle.go | package leetcode
import (
"math"
)
// 解法一 倒序 DP,无辅助空间
func minimumTotal(triangle [][]int) int {
if triangle == nil {
return 0
}
for row := len(triangle) - 2; row >= 0; row-- {
for col := 0; col < len(triangle[row]); col++ {
triangle[row][col] += min(triangle[row+1][col], triangle[row+1][col+1])
}
}
return triangle[0][0]
}
func min(a int, b int) int {
if a > b {
return b
}
return a
}
// 解法二 正常 DP,空间复杂度 O(n)
func minimumTotal1(triangle [][]int) int {
if len(triangle) == 0 {
return 0
}
dp, minNum, index := make([]int, len(triangle[len(triangle)-1])), math.MaxInt64, 0
for ; index < len(triangle[0]); index++ {
dp[index] = triangle[0][index]
}
for i := 1; i < len(triangle); i++ {
for j := len(triangle[i]) - 1; j >= 0; j-- {
if j == 0 {
// 最左边
dp[j] += triangle[i][0]
} else if j == len(triangle[i])-1 {
// 最右边
dp[j] += dp[j-1] + triangle[i][j]
} else {
// 中间
dp[j] = min(dp[j-1]+triangle[i][j], dp[j]+triangle[i][j])
}
}
}
for i := 0; i < len(dp); i++ {
if dp[i] < minNum {
minNum = dp[i]
}
}
return minNum
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0120.Triangle/120. Triangle_test.go | leetcode/0120.Triangle/120. Triangle_test.go | package leetcode
import (
"fmt"
"testing"
)
type question120 struct {
para120
ans120
}
// para 是参数
// one 代表第一个参数
type para120 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans120 struct {
one int
}
func Test_Problem120(t *testing.T) {
qs := []question120{
{
para120{[][]int{{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}}},
ans120{11},
},
}
fmt.Printf("------------------------Leetcode Problem 120------------------------\n")
for _, q := range qs {
_, p := q.ans120, q.para120
fmt.Printf("【input】:%v 【output】:%v\n", p, minimumTotal(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/0453.Minimum-Moves-to-Equal-Array-Elements/453. Minimum Moves to Equal Array Elements_test.go | leetcode/0453.Minimum-Moves-to-Equal-Array-Elements/453. Minimum Moves to Equal Array Elements_test.go | package leetcode
import (
"fmt"
"testing"
)
type question453 struct {
para453
ans453
}
// para 是参数
// one 代表第一个参数
type para453 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans453 struct {
one int
}
func Test_Problem453(t *testing.T) {
qs := []question453{
{
para453{[]int{4, 3, 2, 7, 8, 2, 3, 1}},
ans453{22},
},
{
para453{[]int{1, 2, 3}},
ans453{3},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 453------------------------\n")
for _, q := range qs {
_, p := q.ans453, q.para453
fmt.Printf("【input】:%v 【output】:%v\n", p, minMoves(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/0453.Minimum-Moves-to-Equal-Array-Elements/453. Minimum Moves to Equal Array Elements.go | leetcode/0453.Minimum-Moves-to-Equal-Array-Elements/453. Minimum Moves to Equal Array Elements.go | package leetcode
import "math"
func minMoves(nums []int) int {
sum, min, l := 0, math.MaxInt32, len(nums)
for _, v := range nums {
sum += v
if min > v {
min = v
}
}
return sum - min*l
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0113.Path-Sum-II/113. Path Sum II.go | leetcode/0113.Path-Sum-II/113. Path Sum II.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 pathSum(root *TreeNode, sum int) [][]int {
var slice [][]int
slice = findPath(root, sum, slice, []int(nil))
return slice
}
func findPath(n *TreeNode, sum int, slice [][]int, stack []int) [][]int {
if n == nil {
return slice
}
sum -= n.Val
stack = append(stack, n.Val)
if sum == 0 && n.Left == nil && n.Right == nil {
slice = append(slice, append([]int{}, stack...))
stack = stack[:len(stack)-1]
}
slice = findPath(n.Left, sum, slice, stack)
slice = findPath(n.Right, sum, slice, stack)
return slice
}
// 解法二
func pathSum1(root *TreeNode, sum int) [][]int {
if root == nil {
return [][]int{}
}
if root.Left == nil && root.Right == nil {
if sum == root.Val {
return [][]int{{root.Val}}
}
}
path, res := []int{}, [][]int{}
tmpLeft := pathSum(root.Left, sum-root.Val)
path = append(path, root.Val)
if len(tmpLeft) > 0 {
for i := 0; i < len(tmpLeft); i++ {
tmpLeft[i] = append(path, tmpLeft[i]...)
}
res = append(res, tmpLeft...)
}
path = []int{}
tmpRight := pathSum(root.Right, sum-root.Val)
path = append(path, root.Val)
if len(tmpRight) > 0 {
for i := 0; i < len(tmpRight); i++ {
tmpRight[i] = append(path, tmpRight[i]...)
}
res = append(res, tmpRight...)
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0113.Path-Sum-II/113. Path Sum II_test.go | leetcode/0113.Path-Sum-II/113. Path Sum II_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question113 struct {
para113
ans113
}
// para 是参数
// one 代表第一个参数
type para113 struct {
one []int
sum int
}
// ans 是答案
// one 代表第一个答案
type ans113 struct {
one [][]int
}
func Test_Problem113(t *testing.T) {
qs := []question113{
{
para113{[]int{1, 0, 1, 1, 2, 0, -1, 0, 1, -1, 0, -1, 0, 1, 0}, 2},
ans113{[][]int{{1, 0, 1, 0}, {1, 0, 2, -1}, {1, 1, 0, 0}, {1, 1, -1, 1}}},
},
{
para113{[]int{}, 0},
ans113{[][]int{{}}},
},
{
para113{[]int{5, 4, 8, 11, structures.NULL, 13, 4, 7, 2, structures.NULL, structures.NULL, 5, 1}, 22},
ans113{[][]int{{5, 4, 11, 2}, {5, 8, 4, 5}}},
},
}
fmt.Printf("------------------------Leetcode Problem 113------------------------\n")
for _, q := range qs {
_, p := q.ans113, q.para113
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", pathSum(root, p.sum))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.