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/0129.Sum-Root-to-Leaf-Numbers/129. Sum Root to Leaf Numbers_test.go | leetcode/0129.Sum-Root-to-Leaf-Numbers/129. Sum Root to Leaf Numbers_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question129 struct {
para129
ans129
}
// para 是参数
// one 代表第一个参数
type para129 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans129 struct {
one int
}
func Test_Problem129(t *testing.T) {
qs := []question129{
{
para129{[]int{}},
ans129{0},
},
{
para129{[]int{1, 2, 3}},
ans129{25},
},
{
para129{[]int{4, 9, 0, 5, 1}},
ans129{1026},
},
}
fmt.Printf("------------------------Leetcode Problem 129------------------------\n")
for _, q := range qs {
_, p := q.ans129, q.para129
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", sumNumbers(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/0129.Sum-Root-to-Leaf-Numbers/129. Sum Root to Leaf Numbers.go | leetcode/0129.Sum-Root-to-Leaf-Numbers/129. Sum Root to Leaf Numbers.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 sumNumbers(root *TreeNode) int {
res := 0
dfs(root, 0, &res)
return res
}
func dfs(root *TreeNode, sum int, res *int) {
if root == nil {
return
}
sum = sum*10 + root.Val
if root.Left == nil && root.Right == nil {
*res += sum
return
}
dfs(root.Left, sum, res)
dfs(root.Right, sum, res)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0201.Bitwise-AND-of-Numbers-Range/201. Bitwise AND of Numbers Range.go | leetcode/0201.Bitwise-AND-of-Numbers-Range/201. Bitwise AND of Numbers Range.go | package leetcode
// 解法一
func rangeBitwiseAnd1(m int, n int) int {
if m == 0 {
return 0
}
moved := 0
for m != n {
m >>= 1
n >>= 1
moved++
}
return m << uint32(moved)
}
// 解法二 Brian Kernighan's algorithm
func rangeBitwiseAnd(m int, n int) int {
for n > m {
n &= (n - 1) // 清除最低位的 1
}
return n
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0201.Bitwise-AND-of-Numbers-Range/201. Bitwise AND of Numbers Range_test.go | leetcode/0201.Bitwise-AND-of-Numbers-Range/201. Bitwise AND of Numbers Range_test.go | package leetcode
import (
"fmt"
"testing"
)
type question201 struct {
para201
ans201
}
// para 是参数
// one 代表第一个参数
type para201 struct {
m int
n int
}
// ans 是答案
// one 代表第一个答案
type ans201 struct {
one int
}
func Test_Problem201(t *testing.T) {
qs := []question201{
{
para201{5, 7},
ans201{4},
},
{
para201{0, 1},
ans201{0},
},
}
fmt.Printf("------------------------Leetcode Problem 201------------------------\n")
for _, q := range qs {
_, p := q.ans201, q.para201
fmt.Printf("【input】:%v 【output】:%v\n", p, rangeBitwiseAnd(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/1705.Maximum-Number-of-Eaten-Apples/1705.Maximum Number of Eaten Apples_test.go | leetcode/1705.Maximum-Number-of-Eaten-Apples/1705.Maximum Number of Eaten Apples_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1705 struct {
para1705
ans1705
}
// para 是参数
type para1705 struct {
apples []int
days []int
}
// ans 是答案
type ans1705 struct {
ans int
}
func Test_Problem1705(t *testing.T) {
qs := []question1705{
{
para1705{[]int{1, 2, 3, 5, 2}, []int{3, 2, 1, 4, 2}},
ans1705{7},
},
{
para1705{[]int{3, 0, 0, 0, 0, 2}, []int{3, 0, 0, 0, 0, 2}},
ans1705{5},
},
}
fmt.Printf("------------------------Leetcode Problem 1705------------------------\n")
for _, q := range qs {
_, p := q.ans1705, q.para1705
fmt.Printf("【input】:%v 【output】:%v\n", p, eatenApples(p.apples, p.days))
}
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/1705.Maximum-Number-of-Eaten-Apples/1705.Maximum Number of Eaten Apples.go | leetcode/1705.Maximum-Number-of-Eaten-Apples/1705.Maximum Number of Eaten Apples.go | package leetcode
import "container/heap"
func eatenApples(apples []int, days []int) int {
h := hp{}
i := 0
var ans int
for ; i < len(apples); i++ {
for len(h) > 0 && h[0].end <= i {
heap.Pop(&h)
}
if apples[i] > 0 {
heap.Push(&h, data{apples[i], i + days[i]})
}
if len(h) > 0 {
minData := heap.Pop(&h).(data)
ans++
if minData.left > 1 {
heap.Push(&h, data{minData.left - 1, minData.end})
}
}
}
for len(h) > 0 {
for len(h) > 0 && h[0].end <= i {
heap.Pop(&h)
}
if len(h) == 0 {
break
}
minData := heap.Pop(&h).(data)
nums := min(minData.left, minData.end-i)
ans += nums
i += nums
}
return ans
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
type data struct {
left int
end int
}
type hp []data
func (h hp) Len() int { return len(h) }
func (h hp) Less(i, j int) bool { return h[i].end < h[j].end }
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(x interface{}) {
*h = append(*h, x.(data))
}
func (h *hp) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0890.Find-and-Replace-Pattern/890. Find and Replace Pattern.go | leetcode/0890.Find-and-Replace-Pattern/890. Find and Replace Pattern.go | package leetcode
func findAndReplacePattern(words []string, pattern string) []string {
res := make([]string, 0)
for _, word := range words {
if match(word, pattern) {
res = append(res, word)
}
}
return res
}
func match(w, p string) bool {
if len(w) != len(p) {
return false
}
m, used := make(map[uint8]uint8), make(map[uint8]bool)
for i := 0; i < len(w); i++ {
if v, ok := m[p[i]]; ok {
if w[i] != v {
return false
}
} else {
if used[w[i]] {
return false
}
m[p[i]] = w[i]
used[w[i]] = true
}
}
return true
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0890.Find-and-Replace-Pattern/890. Find and Replace Pattern_test.go | leetcode/0890.Find-and-Replace-Pattern/890. Find and Replace Pattern_test.go | package leetcode
import (
"fmt"
"testing"
)
type question890 struct {
para890
ans890
}
// para 是参数
// one 代表第一个参数
type para890 struct {
words []string
pattern string
}
// ans 是答案
// one 代表第一个答案
type ans890 struct {
one []string
}
func Test_Problem890(t *testing.T) {
qs := []question890{
{
para890{[]string{"abc", "deq", "mee", "aqq", "dkd", "ccc"}, "abb"},
ans890{[]string{"mee", "aqq"}},
},
{
para890{[]string{"a", "b", "c"}, "a"},
ans890{[]string{"a", "b", "c"}},
},
}
fmt.Printf("------------------------Leetcode Problem 890------------------------\n")
for _, q := range qs {
_, p := q.ans890, q.para890
fmt.Printf("【input】:%v 【output】:%v\n", p, findAndReplacePattern(p.words, p.pattern))
}
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/0023.Merge-k-Sorted-Lists/23. Merge k Sorted Lists_test.go | leetcode/0023.Merge-k-Sorted-Lists/23. Merge k Sorted Lists_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question23 struct {
para23
ans23
}
// para 是参数
// one 代表第一个参数
type para23 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans23 struct {
one []int
}
func Test_Problem23(t *testing.T) {
qs := []question23{
{
para23{[][]int{}},
ans23{[]int{}},
},
{
para23{[][]int{
{1},
{1},
}},
ans23{[]int{1, 1}},
},
{
para23{[][]int{
{1, 2, 3, 4},
{1, 2, 3, 4},
}},
ans23{[]int{1, 1, 2, 2, 3, 3, 4, 4}},
},
{
para23{[][]int{
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5},
}},
ans23{[]int{1, 1, 2, 2, 3, 3, 4, 4, 5, 5}},
},
{
para23{[][]int{
{1},
{9, 9, 9, 9, 9},
}},
ans23{[]int{1, 9, 9, 9, 9, 9}},
},
{
para23{[][]int{
{9, 9, 9, 9, 9},
{1},
}},
ans23{[]int{1, 9, 9, 9, 9, 9}},
},
{
para23{[][]int{
{2, 3, 4},
{4, 5, 6},
}},
ans23{[]int{2, 3, 4, 4, 5, 6}},
},
{
para23{[][]int{
{1, 3, 8},
{1, 7},
}},
ans23{[]int{1, 1, 3, 7, 8}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 23------------------------\n")
for _, q := range qs {
var ls []*ListNode
for _, qq := range q.para23.one {
ls = append(ls, structures.Ints2List(qq))
}
fmt.Printf("【input】:%v 【output】:%v\n", q.para23.one, structures.List2Ints(mergeKLists(ls)))
}
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/0023.Merge-k-Sorted-Lists/23. Merge k Sorted Lists.go | leetcode/0023.Merge-k-Sorted-Lists/23. Merge k Sorted Lists.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 mergeKLists(lists []*ListNode) *ListNode {
length := len(lists)
if length < 1 {
return nil
}
if length == 1 {
return lists[0]
}
num := length / 2
left := mergeKLists(lists[:num])
right := mergeKLists(lists[num:])
return mergeTwoLists1(left, right)
}
func mergeTwoLists1(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
if l1.Val < l2.Val {
l1.Next = mergeTwoLists1(l1.Next, l2)
return l1
}
l2.Next = mergeTwoLists1(l1, l2.Next)
return l2
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1654.Minimum-Jumps-to-Reach-Home/1654. Minimum Jumps to Reach Home_test.go | leetcode/1654.Minimum-Jumps-to-Reach-Home/1654. Minimum Jumps to Reach Home_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1654 struct {
para1654
ans1654
}
// para 是参数
// one 代表第一个参数
type para1654 struct {
forbidden []int
a int
b int
x int
}
// ans 是答案
// one 代表第一个答案
type ans1654 struct {
one int
}
func Test_Problem1654(t *testing.T) {
qs := []question1654{
{
para1654{[]int{14, 4, 18, 1, 15}, 3, 15, 9},
ans1654{3},
},
{
para1654{[]int{8, 3, 16, 6, 12, 20}, 15, 13, 11},
ans1654{-1},
},
{
para1654{[]int{1, 6, 2, 14, 5, 17, 4}, 16, 9, 7},
ans1654{2},
},
{
para1654{[]int{1998}, 1999, 2000, 2000},
ans1654{3998},
},
}
fmt.Printf("------------------------Leetcode Problem 1654------------------------\n")
for _, q := range qs {
_, p := q.ans1654, q.para1654
fmt.Printf("【input】:%v 【output】:%v \n", p, minimumJumps(p.forbidden, p.a, p.b, p.x))
}
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/1654.Minimum-Jumps-to-Reach-Home/1654. Minimum Jumps to Reach Home.go | leetcode/1654.Minimum-Jumps-to-Reach-Home/1654. Minimum Jumps to Reach Home.go | package leetcode
func minimumJumps(forbidden []int, a int, b int, x int) int {
visited := make([]bool, 6000)
for i := range forbidden {
visited[forbidden[i]] = true
}
queue, res := [][2]int{{0, 0}}, -1
for len(queue) > 0 {
length := len(queue)
res++
for i := 0; i < length; i++ {
cur, isBack := queue[i][0], queue[i][1]
if cur == x {
return res
}
if isBack == 0 && cur-b > 0 && !visited[cur-b] {
visited[cur-b] = true
queue = append(queue, [2]int{cur - b, 1})
}
if cur+a < len(visited) && !visited[cur+a] {
visited[cur+a] = true
queue = append(queue, [2]int{cur + a, 0})
}
}
queue = queue[length:]
}
return -1
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1664.Ways-to-Make-a-Fair-Array/1664. Ways to Make a Fair Array.go | leetcode/1664.Ways-to-Make-a-Fair-Array/1664. Ways to Make a Fair Array.go | package leetcode
// 解法一 超简洁写法
func waysToMakeFair(nums []int) int {
sum, res := [2]int{}, 0
for i := 0; i < len(nums); i++ {
sum[i%2] += nums[i]
}
for i := 0; i < len(nums); i++ {
sum[i%2] -= nums[i]
if sum[i%2] == sum[1-(i%2)] {
res++
}
sum[1-(i%2)] += nums[i]
}
return res
}
// 解法二 前缀和,后缀和
func waysToMakeFair1(nums []int) int {
evenPrefix, oddPrefix, evenSuffix, oddSuffix, res := 0, 0, 0, 0, 0
for i := 0; i < len(nums); i++ {
if i%2 == 0 {
evenSuffix += nums[i]
} else {
oddSuffix += nums[i]
}
}
for i := 0; i < len(nums); i++ {
if i%2 == 0 {
evenSuffix -= nums[i]
} else {
oddSuffix -= nums[i]
}
if (evenPrefix + oddSuffix) == (oddPrefix + evenSuffix) {
res++
}
if i%2 == 0 {
evenPrefix += nums[i]
} else {
oddPrefix += nums[i]
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1664.Ways-to-Make-a-Fair-Array/1664. Ways to Make a Fair Array_test.go | leetcode/1664.Ways-to-Make-a-Fair-Array/1664. Ways to Make a Fair Array_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1664 struct {
para1664
ans1664
}
// para 是参数
// one 代表第一个参数
type para1664 struct {
nums []int
}
// ans 是答案
// one 代表第一个答案
type ans1664 struct {
one int
}
func Test_Problem1664(t *testing.T) {
qs := []question1664{
{
para1664{[]int{6, 1, 7, 4, 1}},
ans1664{0},
},
{
para1664{[]int{2, 1, 6, 4}},
ans1664{1},
},
{
para1664{[]int{1, 1, 1}},
ans1664{3},
},
{
para1664{[]int{1, 2, 3}},
ans1664{0},
},
}
fmt.Printf("------------------------Leetcode Problem 1664------------------------\n")
for _, q := range qs {
_, p := q.ans1664, q.para1664
fmt.Printf("【input】:%v 【output】:%v \n", p, waysToMakeFair(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/0385.Mini-Parser/385. Mini Parser.go | leetcode/0385.Mini-Parser/385. Mini Parser.go | package leetcode
import (
"fmt"
"strconv"
)
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* type NestedInteger struct {
* }
*
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* func (n NestedInteger) IsInteger() bool {}
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* // So before calling this method, you should have a check
* func (n NestedInteger) GetInteger() int {}
*
* // Set this NestedInteger to hold a single integer.
* func (n *NestedInteger) SetInteger(value int) {}
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* func (n *NestedInteger) Add(elem NestedInteger) {}
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The list length is zero if this NestedInteger holds a single integer
* // You can access NestedInteger's List element directly if you want to modify it
* func (n NestedInteger) GetList() []*NestedInteger {}
*/
// NestedInteger define
type NestedInteger struct {
Num int
List []*NestedInteger
}
// IsInteger define
func (n NestedInteger) IsInteger() bool {
if n.List == nil {
return true
}
return false
}
// GetInteger define
func (n NestedInteger) GetInteger() int {
return n.Num
}
// SetInteger define
func (n *NestedInteger) SetInteger(value int) {
n.Num = value
}
// Add define
func (n *NestedInteger) Add(elem NestedInteger) {
n.List = append(n.List, &elem)
}
// GetList define
func (n NestedInteger) GetList() []*NestedInteger {
return n.List
}
// Print define
func (n NestedInteger) Print() {
if len(n.List) != 0 {
for _, v := range n.List {
if len(v.List) != 0 {
v.Print()
return
}
fmt.Printf("%v ", v.Num)
}
} else {
fmt.Printf("%v ", n.Num)
}
fmt.Printf("\n")
}
func deserialize(s string) *NestedInteger {
stack, cur := []*NestedInteger{}, &NestedInteger{}
for i := 0; i < len(s); {
switch {
case isDigital(s[i]) || s[i] == '-':
j := 0
for j = i + 1; j < len(s) && isDigital(s[j]); j++ {
}
num, _ := strconv.Atoi(s[i:j])
next := &NestedInteger{}
next.SetInteger(num)
if len(stack) > 0 {
stack[len(stack)-1].List = append(stack[len(stack)-1].GetList(), next)
} else {
cur = next
}
i = j
case s[i] == '[':
next := &NestedInteger{}
if len(stack) > 0 {
stack[len(stack)-1].List = append(stack[len(stack)-1].GetList(), next)
}
stack = append(stack, next)
i++
case s[i] == ']':
cur = stack[len(stack)-1]
stack = stack[:len(stack)-1]
i++
case s[i] == ',':
i++
}
}
return cur
}
func isDigital(v byte) bool {
if v >= '0' && v <= '9' {
return true
}
return false
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0385.Mini-Parser/385. Mini Parser_test.go | leetcode/0385.Mini-Parser/385. Mini Parser_test.go | package leetcode
import (
"fmt"
"testing"
)
type question385 struct {
para385
ans385
}
// para 是参数
// one 代表第一个参数
type para385 struct {
n string
}
// ans 是答案
// one 代表第一个答案
type ans385 struct {
one []int
}
func Test_Problem385(t *testing.T) {
qs := []question385{
{
para385{"[[]]"},
ans385{[]int{}},
},
{
para385{"[]"},
ans385{[]int{}},
},
{
para385{"[-1]"},
ans385{[]int{-1}},
},
{
para385{"[123,[456,[789]]]"},
ans385{[]int{123, 456, 789}},
},
{
para385{"324"},
ans385{[]int{324}},
},
}
fmt.Printf("------------------------Leetcode Problem 385------------------------\n")
for _, q := range qs {
_, p := q.ans385, q.para385
fmt.Printf("【input】:%v 【output】: \n", p)
fmt.Printf("NestedInteger = ")
deserialize(p.n).Print()
}
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/0563.Binary-Tree-Tilt/563. Binary Tree Tilt.go | leetcode/0563.Binary-Tree-Tilt/563. Binary Tree Tilt.go | package leetcode
import (
"math"
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findTilt(root *TreeNode) int {
if root == nil {
return 0
}
sum := 0
findTiltDFS(root, &sum)
return sum
}
func findTiltDFS(root *TreeNode, sum *int) int {
if root == nil {
return 0
}
left := findTiltDFS(root.Left, sum)
right := findTiltDFS(root.Right, sum)
*sum += int(math.Abs(float64(left) - float64(right)))
return root.Val + left + right
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0563.Binary-Tree-Tilt/563. Binary Tree Tilt_test.go | leetcode/0563.Binary-Tree-Tilt/563. Binary Tree Tilt_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question563 struct {
para563
ans563
}
// para 是参数
// one 代表第一个参数
type para563 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans563 struct {
one int
}
func Test_Problem563(t *testing.T) {
qs := []question563{
{
para563{[]int{}},
ans563{0},
},
{
para563{[]int{1}},
ans563{0},
},
{
para563{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}},
ans563{41},
},
{
para563{[]int{1, 2, 3, 4, structures.NULL, structures.NULL, 5}},
ans563{11},
},
{
para563{[]int{1, 2, 3, 4, structures.NULL, 5}},
ans563{11},
},
}
fmt.Printf("------------------------Leetcode Problem 563------------------------\n")
for _, q := range qs {
_, p := q.ans563, q.para563
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", findTilt(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/0576.Out-of-Boundary-Paths/576. Out of Boundary Paths_test.go | leetcode/0576.Out-of-Boundary-Paths/576. Out of Boundary Paths_test.go | package leetcode
import (
"fmt"
"testing"
)
type question576 struct {
para576
ans576
}
// para 是参数
// one 代表第一个参数
type para576 struct {
m int
n int
maxMove int
startRow int
startColumn int
}
// ans 是答案
// one 代表第一个答案
type ans576 struct {
one int
}
func Test_Problem576(t *testing.T) {
qs := []question576{
{
para576{2, 2, 2, 0, 0},
ans576{6},
},
{
para576{1, 3, 3, 0, 1},
ans576{12},
},
}
fmt.Printf("------------------------Leetcode Problem 576------------------------\n")
for _, q := range qs {
_, p := q.ans576, q.para576
fmt.Printf("【input】:%v 【output】:%v\n", p, findPaths(p.m, p.n, p.maxMove, p.startRow, p.startColumn))
}
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/0576.Out-of-Boundary-Paths/576. Out of Boundary Paths.go | leetcode/0576.Out-of-Boundary-Paths/576. Out of Boundary Paths.go | package leetcode
var dir = [][]int{
{-1, 0},
{0, 1},
{1, 0},
{0, -1},
}
func findPaths(m int, n int, maxMove int, startRow int, startColumn int) int {
visited := make([][][]int, m)
for i := range visited {
visited[i] = make([][]int, n)
for j := range visited[i] {
visited[i][j] = make([]int, maxMove+1)
for l := range visited[i][j] {
visited[i][j][l] = -1
}
}
}
return dfs(startRow, startColumn, maxMove, m, n, visited)
}
func dfs(x, y, maxMove, m, n int, visited [][][]int) int {
if x < 0 || x >= m || y < 0 || y >= n {
return 1
}
if maxMove == 0 {
visited[x][y][maxMove] = 0
return 0
}
if visited[x][y][maxMove] >= 0 {
return visited[x][y][maxMove]
}
res := 0
for i := 0; i < 4; i++ {
nx := x + dir[i][0]
ny := y + dir[i][1]
res += (dfs(nx, ny, maxMove-1, m, n, visited) % 1000000007)
}
visited[x][y][maxMove] = res % 1000000007
return visited[x][y][maxMove]
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0480.Sliding-Window-Median/480. Sliding Window Median_test.go | leetcode/0480.Sliding-Window-Median/480. Sliding Window Median_test.go | package leetcode
import (
"fmt"
"testing"
)
type question480 struct {
para480
ans480
}
// para 是参数
// one 代表第一个参数
type para480 struct {
one []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans480 struct {
one []int
}
func Test_Problem480(t *testing.T) {
qs := []question480{
{
para480{[]int{1, 3, -1, -3, 5, 3, 6, 7}, 3},
ans480{[]int{1, -1, -1, 3, 5, 6}},
},
}
fmt.Printf("------------------------Leetcode Problem 480------------------------\n")
for _, q := range qs {
_, p := q.ans480, q.para480
fmt.Printf("【input】:%v 【output】:%v\n", p, medianSlidingWindow1(p.one, p.k))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0480.Sliding-Window-Median/480. Sliding Window Median.go | leetcode/0480.Sliding-Window-Median/480. Sliding Window Median.go | package leetcode
import (
"container/heap"
"container/list"
"sort"
)
// 解法一 用链表按照题意实现 时间复杂度 O(n * k) 空间复杂度 O(k)
func medianSlidingWindow(nums []int, k int) []float64 {
var res []float64
w := getWindowList(nums[:k], k)
res = append(res, getMedian(w, k))
for p1 := k; p1 < len(nums); p1++ {
w = removeFromWindow(w, nums[p1-k])
w = insertInWindow(w, nums[p1])
res = append(res, getMedian(w, k))
}
return res
}
func getWindowList(nums []int, k int) *list.List {
s := make([]int, k)
copy(s, nums)
sort.Ints(s)
l := list.New()
for _, n := range s {
l.PushBack(n)
}
return l
}
func removeFromWindow(w *list.List, n int) *list.List {
for e := w.Front(); e != nil; e = e.Next() {
if e.Value.(int) == n {
w.Remove(e)
return w
}
}
return w
}
func insertInWindow(w *list.List, n int) *list.List {
for e := w.Front(); e != nil; e = e.Next() {
if e.Value.(int) >= n {
w.InsertBefore(n, e)
return w
}
}
w.PushBack(n)
return w
}
func getMedian(w *list.List, k int) float64 {
e := w.Front()
for i := 0; i < k/2; e, i = e.Next(), i+1 {
}
if k%2 == 1 {
return float64(e.Value.(int))
}
p := e.Prev()
return (float64(e.Value.(int)) + float64(p.Value.(int))) / 2
}
// 解法二 用两个堆实现 时间复杂度 O(n * log k) 空间复杂度 O(k)
// 用两个堆记录窗口内的值
// 大顶堆里面的元素都比小顶堆里面的元素小
// 如果 k 是偶数,那么两个堆都有 k/2 个元素,中间值就是两个堆顶的元素
// 如果 k 是奇数,那么小顶堆比大顶堆多一个元素,中间值就是小顶堆的堆顶元素
// 删除一个元素,元素都标记到删除的堆中,取 top 的时候注意需要取出没有删除的元素
func medianSlidingWindow1(nums []int, k int) []float64 {
ans := []float64{}
minH := MinHeapR{}
maxH := MaxHeapR{}
if minH.Len() > maxH.Len()+1 {
maxH.Push(minH.Pop())
} else if minH.Len() < maxH.Len() {
minH.Push(maxH.Pop())
}
for i := range nums {
if minH.Len() == 0 || nums[i] >= minH.Top() {
minH.Push(nums[i])
} else {
maxH.Push(nums[i])
}
if i >= k {
if nums[i-k] >= minH.Top() {
minH.Remove(nums[i-k])
} else {
maxH.Remove(nums[i-k])
}
}
if minH.Len() > maxH.Len()+1 {
maxH.Push(minH.Pop())
} else if minH.Len() < maxH.Len() {
minH.Push(maxH.Pop())
}
if minH.Len()+maxH.Len() == k {
if k%2 == 0 {
ans = append(ans, float64(minH.Top()+maxH.Top())/2.0)
} else {
ans = append(ans, float64(minH.Top()))
}
}
// fmt.Printf("%+v, %+v\n", minH, maxH)
}
return ans
}
// IntHeap define
type IntHeap struct {
data []int
}
// Len define
func (h IntHeap) Len() int { return len(h.data) }
// Swap define
func (h IntHeap) Swap(i, j int) { h.data[i], h.data[j] = h.data[j], h.data[i] }
// Push define
func (h *IntHeap) Push(x interface{}) { h.data = append(h.data, x.(int)) }
// Pop define
func (h *IntHeap) Pop() interface{} {
x := h.data[h.Len()-1]
h.data = h.data[0 : h.Len()-1]
return x
}
// Top defines
func (h IntHeap) Top() int {
return h.data[0]
}
// MinHeap define
type MinHeap struct {
IntHeap
}
// Less define
func (h MinHeap) Less(i, j int) bool { return h.data[i] < h.data[j] }
// MaxHeap define
type MaxHeap struct {
IntHeap
}
// Less define
func (h MaxHeap) Less(i, j int) bool { return h.data[i] > h.data[j] }
// MinHeapR define
type MinHeapR struct {
hp, hpDel MinHeap
}
// Len define
func (h MinHeapR) Len() int { return h.hp.Len() - h.hpDel.Len() }
// Top define
func (h *MinHeapR) Top() int {
for h.hpDel.Len() > 0 && h.hp.Top() == h.hpDel.Top() {
heap.Pop(&h.hp)
heap.Pop(&h.hpDel)
}
return h.hp.Top()
}
// Pop define
func (h *MinHeapR) Pop() int {
x := h.Top()
heap.Pop(&h.hp)
return x
}
// Push define
func (h *MinHeapR) Push(x int) { heap.Push(&h.hp, x) }
// Remove define
func (h *MinHeapR) Remove(x int) { heap.Push(&h.hpDel, x) }
// MaxHeapR define
type MaxHeapR struct {
hp, hpDel MaxHeap
}
// Len define
func (h MaxHeapR) Len() int { return h.hp.Len() - h.hpDel.Len() }
// Top define
func (h *MaxHeapR) Top() int {
for h.hpDel.Len() > 0 && h.hp.Top() == h.hpDel.Top() {
heap.Pop(&h.hp)
heap.Pop(&h.hpDel)
}
return h.hp.Top()
}
// Pop define
func (h *MaxHeapR) Pop() int {
x := h.Top()
heap.Pop(&h.hp)
return x
}
// Push define
func (h *MaxHeapR) Push(x int) { heap.Push(&h.hp, x) }
// Remove define
func (h *MaxHeapR) Remove(x int) { heap.Push(&h.hpDel, x) }
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0721.Accounts-Merge/721. Accounts Merge.go | leetcode/0721.Accounts-Merge/721. Accounts Merge.go | package leetcode
import (
"sort"
"github.com/halfrost/LeetCode-Go/template"
)
// 解法一 并查集优化搜索解法
func accountsMerge(accounts [][]string) (r [][]string) {
uf := template.UnionFind{}
uf.Init(len(accounts))
// emailToID 将所有的 email 邮箱都拆开,拆开与 id(数组下标) 对应
// idToName 将 id(数组下标) 与 name 对应
// idToEmails 将 id(数组下标) 与整理好去重以后的 email 组对应
emailToID, idToName, idToEmails, res := make(map[string]int), make(map[int]string), make(map[int][]string), [][]string{}
for id, acc := range accounts {
idToName[id] = acc[0]
for i := 1; i < len(acc); i++ {
pid, ok := emailToID[acc[i]]
if ok {
uf.Union(id, pid)
}
emailToID[acc[i]] = id
}
}
for email, id := range emailToID {
pid := uf.Find(id)
idToEmails[pid] = append(idToEmails[pid], email)
}
for id, emails := range idToEmails {
name := idToName[id]
sort.Strings(emails)
res = append(res, append([]string{name}, emails...))
}
return res
}
// 解法二 并查集暴力解法
func accountsMerge1(accounts [][]string) [][]string {
if len(accounts) == 0 {
return [][]string{}
}
uf, res, visited := template.UnionFind{}, [][]string{}, map[int]bool{}
uf.Init(len(accounts))
for i := 0; i < len(accounts); i++ {
for j := i + 1; j < len(accounts); j++ {
if accounts[i][0] == accounts[j][0] {
tmpA, tmpB, flag := accounts[i][1:], accounts[j][1:], false
for j := 0; j < len(tmpA); j++ {
for k := 0; k < len(tmpB); k++ {
if tmpA[j] == tmpB[k] {
flag = true
break
}
}
if flag {
break
}
}
if flag {
uf.Union(i, j)
}
}
}
}
for i := 0; i < len(accounts); i++ {
if visited[i] {
continue
}
emails, account, tmpMap := accounts[i][1:], []string{accounts[i][0]}, map[string]string{}
for j := i + 1; j < len(accounts); j++ {
if uf.Find(j) == uf.Find(i) {
visited[j] = true
for _, v := range accounts[j][1:] {
tmpMap[v] = v
}
}
}
for _, v := range emails {
tmpMap[v] = v
}
emails = []string{}
for key := range tmpMap {
emails = append(emails, key)
}
sort.Strings(emails)
account = append(account, emails...)
res = append(res, account)
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0721.Accounts-Merge/721. Accounts Merge_test.go | leetcode/0721.Accounts-Merge/721. Accounts Merge_test.go | package leetcode
import (
"fmt"
"testing"
)
type question721 struct {
para721
ans721
}
// para 是参数
// one 代表第一个参数
type para721 struct {
w [][]string
}
// ans 是答案
// one 代表第一个答案
type ans721 struct {
one [][]string
}
func Test_Problem721(t *testing.T) {
qs := []question721{
{
para721{[][]string{{"John", "johnsmith@mail.com", "john00@mail.com"},
{"John", "johnnybravo@mail.com"},
{"John", "johnsmith@mail.com", "john_newyork@mail.com"},
{"Mary", "mary@mail.com"}}},
ans721{[][]string{{"John", "john00@mail.com", "john_newyork@mail.com", "johnsmith@mail.com"},
{"John", "johnnybravo@mail.com"},
{"Mary", "mary@mail.com"}}},
},
{
para721{[][]string{{"Alex", "Alex5@m.co", "Alex4@m.co", "Alex0@m.co"},
{"Ethan", "Ethan3@m.co", "Ethan3@m.co", "Ethan0@m.co"},
{"Kevin", "Kevin4@m.co", "Kevin2@m.co", "Kevin2@m.co"},
{"Gabe", "Gabe0@m.co", "Gabe3@m.co", "Gabe2@m.co"},
{"Gabe", "Gabe3@m.co", "Gabe4@m.co", "Gabe2@m.co"}}},
ans721{[][]string{{"Alex", "Alex0@m.co", "Alex4@m.co", "Alex5@m.co"},
{"Ethan", "Ethan0@m.co", "Ethan3@m.co"},
{"Gabe", "Gabe0@m.co", "Gabe2@m.co", "Gabe3@m.co", "Gabe4@m.co"},
{"Kevin", "Kevin2@m.co", "Kevin4@m.co"}}},
},
{
para721{[][]string{{"David", "David0@m.co", "David4@m.co", "David3@m.co"},
{"David", "David5@m.co", "David5@m.co", "David0@m.co"},
{"David", "David1@m.co", "David4@m.co", "David0@m.co"},
{"David", "David0@m.co", "David1@m.co", "David3@m.co"},
{"David", "David4@m.co", "David1@m.co", "David3@m.co"}}},
ans721{[][]string{{"David", "David0@m.co", "David1@m.co", "David3@m.co", "David4@m.co", "David5@m.co"}}},
},
{
para721{[][]string{}},
ans721{[][]string{}},
},
}
fmt.Printf("------------------------Leetcode Problem 721------------------------\n")
for _, q := range qs {
_, p := q.ans721, q.para721
fmt.Printf("【input】:%v 【output】:%v\n", p, accountsMerge(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/1572.Matrix-Diagonal-Sum/1572.Matrix Diagonal Sum_test.go | leetcode/1572.Matrix-Diagonal-Sum/1572.Matrix Diagonal Sum_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1572 struct {
para1572
ans1572
}
// para 是参数
type para1572 struct {
mat [][]int
}
// ans 是答案
// one 代表第一个答案
type ans1572 struct {
one int
}
func Test_Problem1572(t *testing.T) {
qs := []question1572{
{
para1572{[][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}},
ans1572{25},
},
{
para1572{[][]int{{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}}},
ans1572{8},
},
{
para1572{[][]int{{5}}},
ans1572{5},
},
}
fmt.Printf("------------------------Leetcode Problem 1572------------------------\n")
for _, q := range qs {
_, p := q.ans1572, q.para1572
fmt.Printf("【input】:%v 【output】:%v \n", p, diagonalSum(p.mat))
}
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/1572.Matrix-Diagonal-Sum/1572.Matrix Diagonal Sum.go | leetcode/1572.Matrix-Diagonal-Sum/1572.Matrix Diagonal Sum.go | package leetcode
func diagonalSum(mat [][]int) int {
n := len(mat)
ans := 0
for pi := 0; pi < n; pi++ {
ans += mat[pi][pi]
}
for si, sj := n-1, 0; sj < n; si, sj = si-1, sj+1 {
ans += mat[si][sj]
}
if n%2 == 0 {
return ans
}
return ans - mat[n/2][n/2]
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1108.Defanging-an-IP-Address/1108. Defanging an IP Address.go | leetcode/1108.Defanging-an-IP-Address/1108. Defanging an IP Address.go | package leetcode
import "strings"
func defangIPaddr(address string) string {
return strings.Replace(address, ".", "[.]", -1)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1108.Defanging-an-IP-Address/1108. Defanging an IP Address_test.go | leetcode/1108.Defanging-an-IP-Address/1108. Defanging an IP Address_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1108 struct {
para1108
ans1108
}
// para 是参数
// one 代表第一个参数
type para1108 struct {
one string
}
// ans 是答案
// one 代表第一个答案
type ans1108 struct {
one string
}
func Test_Problem1108(t *testing.T) {
qs := []question1108{
{
para1108{"1.1.1.1"},
ans1108{"1[.]1[.]1[.]1"},
},
{
para1108{"255.100.50.0"},
ans1108{"255[.]100[.]50[.]0"},
},
}
fmt.Printf("------------------------Leetcode Problem 1108------------------------\n")
for _, q := range qs {
_, p := q.ans1108, q.para1108
fmt.Printf("【input】:%v 【output】:%v\n", p, defangIPaddr(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/0676.Implement-Magic-Dictionary/676. Implement Magic Dictionary_test.go | leetcode/0676.Implement-Magic-Dictionary/676. Implement Magic Dictionary_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem676(t *testing.T) {
dict := []string{"hello", "leetcode"}
obj := Constructor676()
obj.BuildDict(dict)
fmt.Printf("obj = %v\n", obj)
fmt.Println(obj.Search("hello"))
fmt.Println(obj.Search("apple"))
fmt.Println(obj.Search("leetcode"))
fmt.Println(obj.Search("leetcoded"))
fmt.Println(obj.Search("hhllo"))
fmt.Println(obj.Search("hell"))
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0676.Implement-Magic-Dictionary/676. Implement Magic Dictionary.go | leetcode/0676.Implement-Magic-Dictionary/676. Implement Magic Dictionary.go | package leetcode
type MagicDictionary struct {
rdict map[int]string
}
/** Initialize your data structure here. */
func Constructor676() MagicDictionary {
return MagicDictionary{rdict: make(map[int]string)}
}
/** Build a dictionary through a list of words */
func (this *MagicDictionary) BuildDict(dict []string) {
for k, v := range dict {
this.rdict[k] = v
}
}
/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
func (this *MagicDictionary) Search(word string) bool {
for _, v := range this.rdict {
n := 0
if len(word) == len(v) {
for i := 0; i < len(v); i++ {
if word[i] != v[i] {
n += 1
}
}
if n == 1 {
return true
}
}
}
return false
}
/**
* Your MagicDictionary object will be instantiated and called as such:
* obj := Constructor();
* obj.BuildDict(dict);
* param_2 := obj.Search(word);
*/
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1670.Design-Front-Middle-Back-Queue/1670. Design Front Middle Back Queue_test.go | leetcode/1670.Design-Front-Middle-Back-Queue/1670. Design Front Middle Back Queue_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem1670(t *testing.T) {
obj := Constructor()
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
obj.PushFront(1)
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
obj.PushBack(2)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.PushMiddle(3)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.PushMiddle(4)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
param1 := obj.PopFront()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
param1 = obj.PopMiddle()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
param1 = obj.PopMiddle()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
param1 = obj.PopBack()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
param1 = obj.PopFront()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
fmt.Printf("-----------------------------------------------------------------\n")
obj = Constructor()
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
obj.PushFront(1)
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
obj.PushFront(2)
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
obj.PushFront(3)
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
obj.PushFront(4)
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
param1 = obj.PopBack()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
param1 = obj.PopBack()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
param1 = obj.PopBack()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
param1 = obj.PopBack()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
fmt.Printf("-----------------------------------------------------------------\n")
obj = Constructor()
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
obj.PushMiddle(1)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.PushMiddle(2)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.PushMiddle(3)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
param1 = obj.PopMiddle()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
param1 = obj.PopMiddle()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
param1 = obj.PopMiddle()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
fmt.Printf("-----------------------------------------------------------------\n")
obj = Constructor()
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
obj.PushMiddle(8)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
param1 = obj.PopMiddle()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
param1 = obj.PopFront()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
param1 = obj.PopBack()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
param1 = obj.PopMiddle()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
obj.PushMiddle(1)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.PushMiddle(10)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
fmt.Printf("-----------------------------------------------------------------\n")
obj = Constructor()
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
param1 = obj.PopMiddle()
fmt.Printf("param1 = %v obj = %v\n", param1, MList2Ints(&obj))
obj.PushMiddle(3)
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
obj.PushFront(6)
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
obj.PushMiddle(6)
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
obj.PushMiddle(3)
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
param1 = obj.PopMiddle()
fmt.Printf("param1 = %v obj = %v %v\n", param1, MList2Ints(&obj), obj)
obj.PushMiddle(7)
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
param1 = obj.PopMiddle()
fmt.Printf("param1 = %v obj = %v %v\n", param1, MList2Ints(&obj), obj)
obj.PushMiddle(8)
fmt.Printf("obj = %v %v\n", MList2Ints(&obj), obj)
// ["FrontMiddleBackQueue","popMiddle","pushMiddle","pushFront","pushMiddle","pushMiddle","popMiddle","pushMiddle","popMiddle","pushMiddle"]
// [[],[],[3],[6],[6],[3],[],[7],[],[8]]
}
func MList2Ints(this *FrontMiddleBackQueue) []int {
array := []int{}
for e := this.list.Front(); e != nil; e = e.Next() {
value, _ := e.Value.(int)
array = append(array, value)
}
return array
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1670.Design-Front-Middle-Back-Queue/1670. Design Front Middle Back Queue.go | leetcode/1670.Design-Front-Middle-Back-Queue/1670. Design Front Middle Back Queue.go | package leetcode
import (
"container/list"
)
type FrontMiddleBackQueue struct {
list *list.List
middle *list.Element
}
func Constructor() FrontMiddleBackQueue {
return FrontMiddleBackQueue{list: list.New()}
}
func (this *FrontMiddleBackQueue) PushFront(val int) {
e := this.list.PushFront(val)
if this.middle == nil {
this.middle = e
} else if this.list.Len()%2 == 0 && this.middle.Prev() != nil {
this.middle = this.middle.Prev()
}
}
func (this *FrontMiddleBackQueue) PushMiddle(val int) {
if this.middle == nil {
this.PushFront(val)
} else {
if this.list.Len()%2 != 0 {
this.middle = this.list.InsertBefore(val, this.middle)
} else {
this.middle = this.list.InsertAfter(val, this.middle)
}
}
}
func (this *FrontMiddleBackQueue) PushBack(val int) {
e := this.list.PushBack(val)
if this.middle == nil {
this.middle = e
} else if this.list.Len()%2 != 0 && this.middle.Next() != nil {
this.middle = this.middle.Next()
}
}
func (this *FrontMiddleBackQueue) PopFront() int {
if this.list.Len() == 0 {
return -1
}
e := this.list.Front()
if this.list.Len() == 1 {
this.middle = nil
} else if this.list.Len()%2 == 0 && this.middle.Next() != nil {
this.middle = this.middle.Next()
}
return this.list.Remove(e).(int)
}
func (this *FrontMiddleBackQueue) PopMiddle() int {
if this.middle == nil {
return -1
}
e := this.middle
if this.list.Len()%2 != 0 {
this.middle = e.Prev()
} else {
this.middle = e.Next()
}
return this.list.Remove(e).(int)
}
func (this *FrontMiddleBackQueue) PopBack() int {
if this.list.Len() == 0 {
return -1
}
e := this.list.Back()
if this.list.Len() == 1 {
this.middle = nil
} else if this.list.Len()%2 != 0 && this.middle.Prev() != nil {
this.middle = this.middle.Prev()
}
return this.list.Remove(e).(int)
}
/**
* Your FrontMiddleBackQueue object will be instantiated and called as such:
* obj := Constructor();
* obj.PushFront(val);
* obj.PushMiddle(val);
* obj.PushBack(val);
* param_4 := obj.PopFront();
* param_5 := obj.PopMiddle();
* param_6 := obj.PopBack();
*/
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0203.Remove-Linked-List-Elements/203. Remove Linked List Elements_test.go | leetcode/0203.Remove-Linked-List-Elements/203. Remove Linked List Elements_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question203 struct {
para203
ans203
}
// para 是参数
// one 代表第一个参数
type para203 struct {
one []int
n int
}
// ans 是答案
// one 代表第一个答案
type ans203 struct {
one []int
}
func Test_Problem203(t *testing.T) {
qs := []question203{
{
para203{[]int{1, 2, 3, 4, 5}, 1},
ans203{[]int{2, 3, 4, 5}},
},
{
para203{[]int{1, 2, 3, 4, 5}, 2},
ans203{[]int{1, 3, 4, 5}},
},
{
para203{[]int{1, 1, 1, 1, 1}, 1},
ans203{[]int{}},
},
{
para203{[]int{1, 2, 3, 2, 3, 2, 3, 2}, 2},
ans203{[]int{1, 3, 3, 3}},
},
{
para203{[]int{1, 2, 3, 4, 5}, 5},
ans203{[]int{1, 2, 3, 4}},
},
{
para203{[]int{}, 5},
ans203{[]int{}},
},
{
para203{[]int{1, 2, 3, 4, 5}, 10},
ans203{[]int{1, 2, 3, 4, 5}},
},
{
para203{[]int{1}, 1},
ans203{[]int{}},
},
}
fmt.Printf("------------------------Leetcode Problem 203------------------------\n")
for _, q := range qs {
_, p := q.ans203, q.para203
fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(removeElements(structures.Ints2List(p.one), 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/0203.Remove-Linked-List-Elements/203. Remove Linked List Elements.go | leetcode/0203.Remove-Linked-List-Elements/203. Remove Linked List Elements.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 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/1038.Binary-Search-Tree-to-Greater-Sum-Tree/1038. Binary Search Tree to Greater Sum Tree.go | leetcode/1038.Binary-Search-Tree-to-Greater-Sum-Tree/1038. Binary Search Tree to Greater Sum Tree.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func bstToGst(root *TreeNode) *TreeNode {
if root == nil {
return root
}
sum := 0
dfs1038(root, &sum)
return root
}
func dfs1038(root *TreeNode, sum *int) {
if root == nil {
return
}
dfs1038(root.Right, sum)
root.Val += *sum
*sum = root.Val
dfs1038(root.Left, sum)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1038.Binary-Search-Tree-to-Greater-Sum-Tree/1038. Binary Search Tree to Greater Sum Tree_test.go | leetcode/1038.Binary-Search-Tree-to-Greater-Sum-Tree/1038. Binary Search Tree to Greater Sum Tree_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question1038 struct {
para1038
ans1038
}
// para 是参数
// one 代表第一个参数
type para1038 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans1038 struct {
one []int
}
func Test_Problem1038(t *testing.T) {
qs := []question1038{
{
para1038{[]int{3, 1, structures.NULL, 0, structures.NULL, -4, structures.NULL, structures.NULL, -2}},
ans1038{[]int{3, 4, structures.NULL, 4, structures.NULL, -2, structures.NULL, structures.NULL, 2}},
},
{
para1038{[]int{2, 1}},
ans1038{[]int{2, 3}},
},
{
para1038{[]int{}},
ans1038{[]int{}},
},
{
para1038{[]int{4, 1, 6, 0, 2, 5, 7, structures.NULL, structures.NULL, structures.NULL, 3, structures.NULL, structures.NULL, structures.NULL, 8}},
ans1038{[]int{30, 36, 21, 36, 35, 26, 15, structures.NULL, structures.NULL, structures.NULL, 33, structures.NULL, structures.NULL, structures.NULL, 8}},
},
{
para1038{[]int{0, structures.NULL, 1}},
ans1038{[]int{1, structures.NULL, 1}},
},
{
para1038{[]int{1, 0, 2}},
ans1038{[]int{3, 3, 2}},
},
{
para1038{[]int{3, 2, 4, 1}},
ans1038{[]int{7, 9, 4, 10}},
},
}
fmt.Printf("------------------------Leetcode Problem 1038------------------------\n")
for _, q := range qs {
_, p := q.ans1038, q.para1038
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", structures.Tree2ints(bstToGst(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/0401.Binary-Watch/401. Binary Watch_test.go | leetcode/0401.Binary-Watch/401. Binary Watch_test.go | package leetcode
import (
"fmt"
"testing"
)
type question401 struct {
para401
ans401
}
// para 是参数
// one 代表第一个参数
type para401 struct {
n int
}
// ans 是答案
// one 代表第一个答案
type ans401 struct {
one []string
}
func Test_Problem401(t *testing.T) {
qs := []question401{
{
para401{1},
ans401{[]string{"1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"}},
},
}
fmt.Printf("------------------------Leetcode Problem 401------------------------\n")
for _, q := range qs {
_, p := q.ans401, q.para401
fmt.Printf("【input】:%v 【output】:%v\n", p, readBinaryWatch(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/0401.Binary-Watch/401. Binary Watch.go | leetcode/0401.Binary-Watch/401. Binary Watch.go | package leetcode
import (
"fmt"
"strconv"
)
// 解法一
func readBinaryWatch(num int) []string {
memo := make([]int, 60)
// count the number of 1 in a binary number
count := func(n int) int {
if memo[n] != 0 {
return memo[n]
}
originN, res := n, 0
for n != 0 {
n = n & (n - 1)
res++
}
memo[originN] = res
return res
}
// fmtMinute format minute 0:1 -> 0:01
fmtMinute := func(m int) string {
if m < 10 {
return "0" + strconv.Itoa(m)
}
return strconv.Itoa(m)
}
var res []string
// traverse 0:00 -> 12:00
for i := 0; i < 12; i++ {
for j := 0; j < 60; j++ {
if count(i)+count(j) == num {
res = append(res, strconv.Itoa(i)+":"+fmtMinute(j))
}
}
}
return res
}
// 解法二 打表
var (
hour = []string{"1", "2", "4", "8"}
minute = []string{"01", "02", "04", "08", "16", "32"}
hourMap = map[int][]string{
0: {"0"},
1: {"1", "2", "4", "8"},
2: {"3", "5", "9", "6", "10"},
3: {"7", "11"},
}
minuteMap = map[int][]string{
0: {"00"},
1: {"01", "02", "04", "08", "16", "32"},
2: {"03", "05", "09", "17", "33", "06", "10", "18", "34", "12", "20", "36", "24", "40", "48"},
3: {"07", "11", "19", "35", "13", "21", "37", "25", "41", "49", "14", "22", "38", "26", "42", "50", "28", "44", "52", "56"},
4: {"15", "23", "39", "27", "43", "51", "29", "45", "53", "57", "30", "46", "54", "58"},
5: {"31", "47", "55", "59"},
}
)
func readBinaryWatch1(num int) []string {
var res []string
if num > 8 {
return res
}
for i := 0; i <= num; i++ {
for j := 0; j < len(hourMap[i]); j++ {
for k := 0; k < len(minuteMap[num-i]); k++ {
res = append(res, hourMap[i][j]+":"+minuteMap[num-i][k])
}
}
}
return res
}
// / ---------------------------------------
// / ---------------------------------------
// / ---------------------------------------
// / ---------------------------------------
// / ---------------------------------------
// 以下是打表用到的函数
// 调用 findReadBinaryWatchMinute(num, 0, c, &res) 打表
func findReadBinaryWatchMinute(target, index int, c []int, res *[]string) {
if target == 0 {
str, tmp := "", 0
for i := 0; i < len(c); i++ {
t, _ := strconv.Atoi(minute[c[i]])
tmp += t
}
if tmp < 10 {
str = "0" + strconv.Itoa(tmp)
} else {
str = strconv.Itoa(tmp)
}
// fmt.Printf("找到解了 c = %v str = %v\n", c, str)
fmt.Printf("\"%v\", ", str)
return
}
for i := index; i < 6; i++ {
c = append(c, i)
findReadBinaryWatchMinute(target-1, i+1, c, res)
c = c[:len(c)-1]
}
}
// 调用 findReadBinaryWatchHour(num, 0, c, &res) 打表
func findReadBinaryWatchHour(target, index int, c []int, res *[]string) {
if target == 0 {
str, tmp := "", 0
for i := 0; i < len(c); i++ {
t, _ := strconv.Atoi(hour[c[i]])
tmp += t
}
str = strconv.Itoa(tmp)
//fmt.Printf("找到解了 c = %v str = %v\n", c, str)
fmt.Printf("\"%v\", ", str)
return
}
for i := index; i < 4; i++ {
c = append(c, i)
findReadBinaryWatchHour(target-1, i+1, c, res)
c = c[:len(c)-1]
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0537.Complex-Number-Multiplication/537. Complex Number Multiplication_test.go | leetcode/0537.Complex-Number-Multiplication/537. Complex Number Multiplication_test.go | package leetcode
import (
"fmt"
"testing"
)
type question537 struct {
para537
ans537
}
// para 是参数
// one 代表第一个参数
type para537 struct {
a string
b string
}
// ans 是答案
// one 代表第一个答案
type ans537 struct {
one string
}
func Test_Problem537(t *testing.T) {
qs := []question537{
{
para537{"1+1i", "1+1i"},
ans537{"0+2i"},
},
{
para537{"1+-1i", "1+-1i"},
ans537{"0+-2i"},
},
}
fmt.Printf("------------------------Leetcode Problem 537------------------------\n")
for _, q := range qs {
_, p := q.ans537, q.para537
fmt.Printf("【input】:%v 【output】:%v\n", p, complexNumberMultiply(p.a, p.b))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0537.Complex-Number-Multiplication/537. Complex Number Multiplication.go | leetcode/0537.Complex-Number-Multiplication/537. Complex Number Multiplication.go | package leetcode
import (
"strconv"
"strings"
)
func complexNumberMultiply(a string, b string) string {
realA, imagA := parse(a)
realB, imagB := parse(b)
real := realA*realB - imagA*imagB
imag := realA*imagB + realB*imagA
return strconv.Itoa(real) + "+" + strconv.Itoa(imag) + "i"
}
func parse(s string) (int, int) {
ss := strings.Split(s, "+")
r, _ := strconv.Atoi(ss[0])
i, _ := strconv.Atoi(ss[1][:len(ss[1])-1])
return r, i
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1048.Longest-String-Chain/1048. Longest String Chain_test.go | leetcode/1048.Longest-String-Chain/1048. Longest String Chain_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1048 struct {
para1048
ans1048
}
// para 是参数
// one 代表第一个参数
type para1048 struct {
words []string
}
// ans 是答案
// one 代表第一个答案
type ans1048 struct {
one int
}
func Test_Problem1048(t *testing.T) {
qs := []question1048{
{
para1048{[]string{"a", "b", "ab", "bac"}},
ans1048{2},
},
{
para1048{[]string{"xbc", "pcxbcf", "xb", "cxbc", "pcxbc"}},
ans1048{5},
},
{
para1048{[]string{"a", "b", "ba", "bca", "bda", "bdca"}},
ans1048{4},
},
{
para1048{[]string{"qjcaeymang", "bqiq", "bcntqiqulagurhz", "lyctmomvis", "bdnhym", "crxrdlv", "wo", "kijftxssyqmui", "abtcrjs", "rceecupq", "crxrdclv", "tvwkxrev", "oc", "lrzzcl", "snpzuykyobci", "abbtczrjs", "rpqojpmv",
"kbfbcjxgvnb", "uqvhuucupu", "fwoquoih", "ezsuqxunx", "biq", "crxrwdclv", "qoyfqhytzxfp", "aryqceercpaupqm", "tvwxrev", "gchusjxz", "uls", "whb", "natdmc", "jvidsf", "yhyz", "smvsitdbutamn", "gcfsghusjsxiz", "ijpyhk", "tzvqwkmzxruevs",
"fwvjxaxrvmfm", "wscxklqmxhn", "velgcy", "lyctomvi", "smvsitbutam", "hfosz", "fuzubrpo", "dfdeidcepshvjn", "twqol", "rpqjpmv", "ijftxssyqmi", "dzuzsainzbsx", "qyzxfp", "tvwkmzxruev", "farfm", "bbwkizqhicip", "wqobtmamvpgluh", "rytspgy",
"uqvheuucdupuw", "jcmang", "h", "kijfhtxssyqmui", "twqgolksq", "rtkgopofnykkrl", "smvstbutam", "xkbfbbcjxgvnbq", "feyq", "oyfqhytzxfp", "velgcby", "dmnioxbf", "kbx", "zx", "wscxkqlqmxbhn", "efvcjtgoiga", "jumttwxv", "zux", "z", "smvsitbutamn",
"jftxssyqmi", "wnlhsaj", "bbwizqhcp", "yctomv", "oyqyzxfp", "wqhc", "jnnwp", "bcntqiquagurz", "qzx", "kbfbjxn", "dmnixbf", "ukqs", "fey", "ryqceecaupq", "smvlsitzdbutamn", "bdnhm", "lrhtwfosrzq", "nkptknldw", "crxrwdclvx", "abbtcwzrjs",
"uqvheuucupu", "abjbtcwbzrjs", "nkmptknldw", "wnulhsbaj", "wnlhsbaj", "wqobtmamvgluh", "jvis", "pcd", "s", "kjuannelajc", "valas", "lrrzzcl", "kjuannelajct", "snyyoc", "jwp", "vbum", "ezuunx", "bcntqiquagur", "vals", "cov", "dfdidcepshvjn",
"vvamlasl", "budnhym", "h", "fwxarvfm", "lrhwfosrz", "nkptnldw", "vjhse", "zzeb", "fubrpo", "fkla", "qjulm", "xpdcdxqia", "ucwxwdm", "jvidsfr", "exhc", "kbfbjx", "bcntqiquaur", "fwnoqjuoihe", "ezsruqxuinrpxc", "ec", "dzuzstuacinzbvsx",
"cxkqmxhn", "egpveohyvq", "bkcv", "dzuzsaizbx", "jftxssymi", "ycov", "zbvbeai", "ch", "atcrjs", "qjcemang", "tvjhsed", "vamlas", "bundnhym", "li", "wnulfhsbaj", "o", "ijhtpyhkrif", "nyoc", "ov", "ryceecupq", "wjcrjnszipc", "lrhtwfosrz",
"tbzngeqcz", "awfotfiqni", "azbw", "o", "gcfghusjsxiz", "uqvheuucdupu", "rypgy", "snpuykyobc", "ckhn", "kbfbcjxgnb", "xkeow", "jvids", "ubnsnusvgmqog", "endjbkjere", "fwarfm", "wvhb", "fwnoqtjuozihe", "jnwp", "awfotfmiyqni", "iv", "ryqceecupq",
"y", "qjuelm", "qyzxp", "vsbum", "dnh", "fam", "snpuyyobc", "wqobtmamvglu", "gjpw", "jcemang", "ukqso", "evhlfz", "nad", "bucwxwdm", "xkabfbbcjxgvnbq", "fwnoqjuozihe", "smvsitzdbutamn", "vec", "fos", "abbtcwbzrjs", "uyifxeyq", "kbfbjxgnb",
"nyyoc", "kcv", "fbundnhym", "tbzngpeqcz", "yekfvcjtgoiga", "rgjpw", "ezgvhsalfz", "yoc", "ezvhsalfz", "crxdlv", "chusjz", "fwxaxrvfm", "dzuzstuacinzbsx", "bwizqhc", "pdcdx", "dmnioxbmf", "zuunx", "oqyzxfp", "ezsruqxuinxc", "qjcaemang", "gcghusjsxiz", "nktnldw",
"qoyfqhytxzxfp", "bwqhc", "btkcvj", "qxpdcdxqia", "kijofhtxssyqmui", "rypy", "helmi", "zkrlexhxbwt", "qobtmamgu", "vhlfz", "rqjpmv", "yhy", "zzembhy", "rjpmv", "jhse", "fosz", "twol", "qbtamu", "nawxxbslyhucqxb", "dzzsaizbx", "dmnijgoxsbmf",
"ijhtpyhkr", "yp", "awfotfgmiyqni", "yctov", "hse", "azabw", "aryqceercaupqm", "fuzubrpoa", "ubnswnusvgmqog", "fafm", "i", "ezvhalfz", "aryxqceercpaupqm", "bwizqhcp", "pdcdxq", "wscxkqlqmxhn", "fuubrpo", "fwvxaxrvmfm", "abjbtcwbzrjas", "zx",
"rxmiirbxemog", "dfdeidcepshvvjqn", "az", "velc", "zkrlexnhxbwt", "nawxbslyhucqxb", "qjugelm", "ijhtpdyhkrif", "dmixbf", "gcfsghtusjsxiz", "juannlajc", "uqvheuucdupmuw", "rpqojpmgxv", "rpqojpmxv", "xppph", "kjuannellajct", "lrhfosrz", "dmnijoxsbmf",
"ckmxhn", "tvijhsed", "dzuzstuainzbsx", "exhvc", "tvwkxruev", "rxmiirbemog", "lhfosz", "fkyla", "tlwqgolksq", "velgcbpy", "bcqiqaur", "xkhfejow", "ezsuqunx", "dmnioxsbmf", "bqiqu", "ijhtpudyhkrif", "xpdcdxqi", "ckh", "nwxbslyhucqxb", "bbwkizqhcip", "pcdx",
"dzuzsuainzbsx", "xkbfbcjxgvnbq", "smvsbutm", "ezsruqxuinrxc", "smvlsitzdbutamdn", "am", "tvwkzxruev", "scxkqmxhn", "snpzuykyobc", "ekfvcjtgoiga", "fuzsubrpoa", "trtkgopofnykkrl", "oyqhytzxfp", "kbjx", "ifeyq", "vhl", "xkfeow", "ezgvhsialfz", "velgc", "hb",
"zbveai", "gcghusjxz", "twqgolkq", "btkcv", "ryqceercaupq", "bi", "vvamlas", "awfotfmiqni", "abbtcrjs", "jutkqesoh", "xkbfbcjxgvnb", "hli", "ryspgy", "endjjjbkjere", "mvsbum", "ckqmxhn", "ezsruqxunxc", "zzeby", "xhc", "ezvhlfz", "ezsruqxunx", "tzvwkmzxruev",
"hlmi", "kbbjx", "uqvhuuupu", "scxklqmxhn", "wqobtmamglu", "xpdcdxq", "qjugelym", "ifxeyq", "bcnqiquaur", "qobtmamglu", "xkabfbbcjxbgvnbq", "fuuzsubrpoa", "tvibjhsed", "oyqhyzxfp", "ijhpyhk", "c", "gcghusjxiz", "exhvoc", "awfotfini", "vhlz", "rtgopofykkrl",
"yh", "ypy", "azb", "bwiqhc", "fla", "dmnijgioxsbmf", "chusjxz", "jvjidsfr", "natddmc", "uifxeyq", "x", "tzvqwkmzxruev", "bucwxwdwm", "ckmhn", "zzemby", "rpmv", "bcntqiqulagurz", "fwoqjuoihe", "dzuzsainzbx", "zkrlehxbwt", "kv", "ucwxwm", "ubnswnusvgmdqog",
"wol", "endjjbkjere", "natyddmc", "vl", "ukqsoh", "ezuqunx", "exhvovc", "bqiqau", "bqiqaur", "zunx", "pc", "snuyyoc", "a", "lrhfosz", "kbfbjxgn", "rtgopofnykkrl", "hehszegkvse", "smvsbum", "ijhpyhkr", "ijftxssyqmui", "lyctomvis", "juanlajc", "jukqesoh",
"xptpph", "fwarvfm", "qbtmamu", "twqgolq", "aryqceercaupq", "qbtmamgu", "rtgopofykkr", "snpuyyoc", "qyzx", "fwvxaxrvfm", "juannelajc", "fwoquoihe", "nadmc", "jumttwxvx", "ijhtpyhkrf", "twqolq", "rpv", "hehszegkuvse", "ls", "tvjhse", "rxmiirbemg",
"dfdeidcepshvvjn", "dnhm", "egpeohyvq", "rgnjpw", "bbwkizqhcp", "nadc", "bcqiquaur", "xkhfeow", "smvstbutm", "ukqesoh", "yctomvi"}},
ans1048{15},
},
}
fmt.Printf("------------------------Leetcode Problem 1048------------------------\n")
for _, q := range qs {
_, p := q.ans1048, q.para1048
fmt.Printf("【input】:%v 【output】:%v\n", p, longestStrChain(p.words))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1048.Longest-String-Chain/1048. Longest String Chain.go | leetcode/1048.Longest-String-Chain/1048. Longest String Chain.go | package leetcode
import "sort"
func longestStrChain(words []string) int {
sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) })
poss, res := make([]int, 16+2), 0
for i, w := range words {
if poss[len(w)] == 0 {
poss[len(w)] = i
}
}
dp := make([]int, len(words))
for i := len(words) - 1; i >= 0; i-- {
dp[i] = 1
for j := poss[len(words[i])+1]; j < len(words) && len(words[j]) == len(words[i])+1; j++ {
if isPredecessor(words[j], words[i]) {
dp[i] = max(dp[i], 1+dp[j])
}
}
res = max(res, dp[i])
}
return res
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func isPredecessor(long, short string) bool {
i, j := 0, 0
wasMismatch := false
for j < len(short) {
if long[i] != short[j] {
if wasMismatch {
return false
}
wasMismatch = true
i++
continue
}
i++
j++
}
return true
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1157.Online-Majority-Element-In-Subarray/1157. Online Majority Element In Subarray.go | leetcode/1157.Online-Majority-Element-In-Subarray/1157. Online Majority Element In Subarray.go | package leetcode
import (
"sort"
)
type segmentItem struct {
candidate int
count int
}
// MajorityChecker define
type MajorityChecker struct {
segmentTree []segmentItem
data []int
merge func(i, j segmentItem) segmentItem
count map[int][]int
}
// Constructor1157 define
func Constructor1157(arr []int) MajorityChecker {
data, tree, mc, count := make([]int, len(arr)), make([]segmentItem, 4*len(arr)), MajorityChecker{}, make(map[int][]int)
// 这个 merge 函数就是摩尔投票算法
mc.merge = func(i, j segmentItem) segmentItem {
if i.candidate == j.candidate {
return segmentItem{candidate: i.candidate, count: i.count + j.count}
}
if i.count > j.count {
return segmentItem{candidate: i.candidate, count: i.count - j.count}
}
return segmentItem{candidate: j.candidate, count: j.count - i.count}
}
for i := 0; i < len(arr); i++ {
data[i] = arr[i]
}
for i := 0; i < len(arr); i++ {
if _, ok := count[arr[i]]; !ok {
count[arr[i]] = []int{}
}
count[arr[i]] = append(count[arr[i]], i)
}
mc.data, mc.segmentTree, mc.count = data, tree, count
if len(arr) > 0 {
mc.buildSegmentTree(0, 0, len(arr)-1)
}
return mc
}
func (mc *MajorityChecker) buildSegmentTree(treeIndex, left, right int) {
if left == right {
mc.segmentTree[treeIndex] = segmentItem{candidate: mc.data[left], count: 1}
return
}
leftTreeIndex, rightTreeIndex := mc.leftChild(treeIndex), mc.rightChild(treeIndex)
midTreeIndex := left + (right-left)>>1
mc.buildSegmentTree(leftTreeIndex, left, midTreeIndex)
mc.buildSegmentTree(rightTreeIndex, midTreeIndex+1, right)
mc.segmentTree[treeIndex] = mc.merge(mc.segmentTree[leftTreeIndex], mc.segmentTree[rightTreeIndex])
}
func (mc *MajorityChecker) leftChild(index int) int {
return 2*index + 1
}
func (mc *MajorityChecker) rightChild(index int) int {
return 2*index + 2
}
// Query define
func (mc *MajorityChecker) query(left, right int) segmentItem {
if len(mc.data) > 0 {
return mc.queryInTree(0, 0, len(mc.data)-1, left, right)
}
return segmentItem{candidate: -1, count: -1}
}
func (mc *MajorityChecker) queryInTree(treeIndex, left, right, queryLeft, queryRight int) segmentItem {
midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, mc.leftChild(treeIndex), mc.rightChild(treeIndex)
if queryLeft <= left && queryRight >= right { // segment completely inside range
return mc.segmentTree[treeIndex]
}
if queryLeft > midTreeIndex {
return mc.queryInTree(rightTreeIndex, midTreeIndex+1, right, queryLeft, queryRight)
} else if queryRight <= midTreeIndex {
return mc.queryInTree(leftTreeIndex, left, midTreeIndex, queryLeft, queryRight)
}
// merge query results
return mc.merge(mc.queryInTree(leftTreeIndex, left, midTreeIndex, queryLeft, midTreeIndex),
mc.queryInTree(rightTreeIndex, midTreeIndex+1, right, midTreeIndex+1, queryRight))
}
// Query define
func (mc *MajorityChecker) Query(left int, right int, threshold int) int {
res := mc.query(left, right)
if _, ok := mc.count[res.candidate]; !ok {
return -1
}
start := sort.Search(len(mc.count[res.candidate]), func(i int) bool { return left <= mc.count[res.candidate][i] })
end := sort.Search(len(mc.count[res.candidate]), func(i int) bool { return right < mc.count[res.candidate][i] }) - 1
if (end - start + 1) >= threshold {
return res.candidate
}
return -1
}
/**
* Your MajorityChecker object will be instantiated and called as such:
* obj := Constructor(arr);
* param_1 := obj.Query(left,right,threshold);
*/
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1157.Online-Majority-Element-In-Subarray/1157. Online Majority Element In Subarray_test.go | leetcode/1157.Online-Majority-Element-In-Subarray/1157. Online Majority Element In Subarray_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem1157(t *testing.T) {
arr := []int{1, 1, 2, 2, 1, 1}
obj := Constructor1157(arr)
fmt.Printf("obj = %v\n", obj)
fmt.Printf("query(0,5,4) = %v\n", obj.Query(0, 5, 4)) //1
fmt.Printf("query(0,3,3) = %v\n", obj.Query(0, 3, 3)) //-1
fmt.Printf("query(2,3,2) = %v\n", obj.Query(2, 3, 2)) //2
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1025.Divisor-Game/1025. Divisor Game.go | leetcode/1025.Divisor-Game/1025. Divisor Game.go | package leetcode
func divisorGame(N int) bool {
return N%2 == 0
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1025.Divisor-Game/1025. Divisor Game_test.go | leetcode/1025.Divisor-Game/1025. Divisor Game_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1025 struct {
para1025
ans1025
}
// para 是参数
// one 代表第一个参数
type para1025 struct {
one int
}
// ans 是答案
// one 代表第一个答案
type ans1025 struct {
one bool
}
func Test_Problem1025(t *testing.T) {
qs := []question1025{
{
para1025{2},
ans1025{true},
},
{
para1025{3},
ans1025{false},
},
}
fmt.Printf("------------------------Leetcode Problem 1025------------------------\n")
for _, q := range qs {
_, p := q.ans1025, q.para1025
fmt.Printf("【input】:%v 【output】:%v\n", p, divisorGame(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/1423.Maximum-Points-You-Can-Obtain-from-Cards/1423. Maximum Points You Can Obtain from Cards.go | leetcode/1423.Maximum-Points-You-Can-Obtain-from-Cards/1423. Maximum Points You Can Obtain from Cards.go | package leetcode
func maxScore(cardPoints []int, k int) int {
windowSize, sum := len(cardPoints)-k, 0
for _, val := range cardPoints[:windowSize] {
sum += val
}
minSum := sum
for i := windowSize; i < len(cardPoints); i++ {
sum += cardPoints[i] - cardPoints[i-windowSize]
if sum < minSum {
minSum = sum
}
}
total := 0
for _, pt := range cardPoints {
total += pt
}
return total - minSum
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1423.Maximum-Points-You-Can-Obtain-from-Cards/1423. Maximum Points You Can Obtain from Cards_test.go | leetcode/1423.Maximum-Points-You-Can-Obtain-from-Cards/1423. Maximum Points You Can Obtain from Cards_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1423 struct {
para1423
ans1423
}
// para 是参数
// one 代表第一个参数
type para1423 struct {
cardPoints []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans1423 struct {
one int
}
func Test_Problem1423(t *testing.T) {
qs := []question1423{
{
para1423{[]int{1, 2, 3, 4, 5, 6, 1}, 3},
ans1423{12},
},
{
para1423{[]int{2, 2, 2}, 2},
ans1423{4},
},
{
para1423{[]int{9, 7, 7, 9, 7, 7, 9}, 7},
ans1423{55},
},
{
para1423{[]int{1, 1000, 1}, 1},
ans1423{1},
},
{
para1423{[]int{1, 79, 80, 1, 1, 1, 200, 1}, 3},
ans1423{202},
},
}
fmt.Printf("------------------------Leetcode Problem 1423------------------------\n")
for _, q := range qs {
_, p := q.ans1423, q.para1423
fmt.Printf("【input】:%v 【output】:%v\n", p, maxScore(p.cardPoints, 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/0213.House-Robber-II/213. House Robber II_test.go | leetcode/0213.House-Robber-II/213. House Robber II_test.go | package leetcode
import (
"fmt"
"testing"
)
type question213 struct {
para213
ans213
}
// para 是参数
// one 代表第一个参数
type para213 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans213 struct {
one int
}
func Test_Problem213(t *testing.T) {
qs := []question213{
{
para213{[]int{0, 0}},
ans213{0},
},
{
para213{[]int{2, 3, 2}},
ans213{3},
},
{
para213{[]int{1, 2, 3, 1}},
ans213{4},
},
}
fmt.Printf("------------------------Leetcode Problem 213------------------------\n")
for _, q := range qs {
_, p := q.ans213, q.para213
fmt.Printf("【input】:%v 【output】:%v\n", p, rob213(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/0213.House-Robber-II/213. House Robber II.go | leetcode/0213.House-Robber-II/213. House Robber II.go | package leetcode
func rob213(nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
if n == 1 {
return nums[0]
}
if n == 2 {
return max(nums[0], nums[1])
}
// 由于首尾是相邻的,所以需要对比 [0,n-1]、[1,n] 这两个区间的最大值
return max(rob213_1(nums, 0, n-2), rob213_1(nums, 1, n-1))
}
func rob213_1(nums []int, start, end int) int {
preMax := nums[start]
curMax := max(preMax, nums[start+1])
for i := start + 2; i <= end; i++ {
tmp := curMax
curMax = max(curMax, nums[i]+preMax)
preMax = tmp
}
return curMax
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096. Step-By-Step Directions From a Binary Tree Node to Another_test.go | leetcode/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096. Step-By-Step Directions From a Binary Tree Node to Another_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question2096 struct {
para2096
ans2096
}
// para 是参数
// one 代表第一个参数
type para2096 struct {
one []int
startValue int
destValue int
}
// ans 是答案
// one 代表第一个答案
type ans2096 struct {
one string
}
func Test_Problem2096(t *testing.T) {
qs := []question2096{
{
para2096{[]int{5, 1, 2, 3, structures.NULL, 6, 4}, 3, 6},
ans2096{"UURL"},
},
{
para2096{[]int{2, 1}, 2, 1},
ans2096{"L"},
},
{
para2096{[]int{1, 2}, 2, 1},
ans2096{"U"},
},
{
para2096{[]int{3, 1, 2}, 2, 1},
ans2096{"UL"},
},
{
para2096{[]int{7, 8, 3, 1, structures.NULL, 4, 5, 6, structures.NULL, structures.NULL, structures.NULL, structures.NULL, structures.NULL, structures.NULL, 2}, 7, 5},
ans2096{"RR"},
},
}
fmt.Printf("------------------------Leetcode Problem 2096------------------------\n")
for _, q := range qs {
_, p := q.ans2096, q.para2096
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", getDirections(root, p.startValue, p.destValue))
}
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/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096. Step-By-Step Directions From a Binary Tree Node to Another.go | leetcode/2096.Step-By-Step-Directions-From-a-Binary-Tree-Node-to-Another/2096. Step-By-Step Directions From a Binary Tree Node to Another.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 getDirections(root *TreeNode, startValue int, destValue int) string {
sPath, dPath := make([]byte, 0), make([]byte, 0)
findPath(root, startValue, &sPath)
findPath(root, destValue, &dPath)
size, i := min(len(sPath), len(dPath)), 0
for i < size {
if sPath[len(sPath)-1-i] == dPath[len(dPath)-1-i] {
i++
} else {
break
}
}
sPath = sPath[:len(sPath)-i]
replace(sPath)
dPath = dPath[:len(dPath)-i]
reverse(dPath)
sPath = append(sPath, dPath...)
return string(sPath)
}
func findPath(root *TreeNode, value int, path *[]byte) bool {
if root.Val == value {
return true
}
if root.Left != nil && findPath(root.Left, value, path) {
*path = append(*path, 'L')
return true
}
if root.Right != nil && findPath(root.Right, value, path) {
*path = append(*path, 'R')
return true
}
return false
}
func reverse(path []byte) {
left, right := 0, len(path)-1
for left < right {
path[left], path[right] = path[right], path[left]
left++
right--
}
}
func replace(path []byte) {
for i := 0; i < len(path); i++ {
path[i] = 'U'
}
}
func min(i, j int) int {
if i < j {
return i
}
return j
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0343.Integer-Break/343. Integer Break.go | leetcode/0343.Integer-Break/343. Integer Break.go | package leetcode
func integerBreak(n int) int {
dp := make([]int, n+1)
dp[0], dp[1] = 1, 1
for i := 1; i <= n; i++ {
for j := 1; j < i; j++ {
// dp[i] = max(dp[i], j * (i - j), j*dp[i-j])
dp[i] = max(dp[i], j*max(dp[i-j], i-j))
}
}
return dp[n]
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0343.Integer-Break/343. Integer Break_test.go | leetcode/0343.Integer-Break/343. Integer Break_test.go | package leetcode
import (
"fmt"
"testing"
)
type question343 struct {
para343
ans343
}
// para 是参数
// one 代表第一个参数
type para343 struct {
one int
}
// ans 是答案
// one 代表第一个答案
type ans343 struct {
one int
}
func Test_Problem343(t *testing.T) {
qs := []question343{
{
para343{2},
ans343{1},
},
{
para343{10},
ans343{36},
},
}
fmt.Printf("------------------------Leetcode Problem 343------------------------\n")
for _, q := range qs {
_, p := q.ans343, q.para343
fmt.Printf("【input】:%v 【output】:%v\n", p, integerBreak(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/1304.Find-N-Unique-Integers-Sum-up-to-Zero/1304. Find N Unique Integers Sum up to Zero_test.go | leetcode/1304.Find-N-Unique-Integers-Sum-up-to-Zero/1304. Find N Unique Integers Sum up to Zero_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1304 struct {
para1304
ans1304
}
// para 是参数
// one 代表第一个参数
type para1304 struct {
one int
}
// ans 是答案
// one 代表第一个答案
type ans1304 struct {
one []int
}
func Test_Problem1304(t *testing.T) {
qs := []question1304{
{
para1304{5},
ans1304{[]int{-7, -1, 1, 3, 4}},
},
{
para1304{0},
ans1304{[]int{}},
},
{
para1304{3},
ans1304{[]int{-1, 0, 1}},
},
{
para1304{1},
ans1304{[]int{0}},
},
}
fmt.Printf("------------------------Leetcode Problem 1304------------------------\n")
for _, q := range qs {
_, p := q.ans1304, q.para1304
fmt.Printf("【input】:%v 【output】:%v\n", p, sumZero(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/1304.Find-N-Unique-Integers-Sum-up-to-Zero/1304. Find N Unique Integers Sum up to Zero.go | leetcode/1304.Find-N-Unique-Integers-Sum-up-to-Zero/1304. Find N Unique Integers Sum up to Zero.go | package leetcode
func sumZero(n int) []int {
res, left, right, start := make([]int, n), 0, n-1, 1
for left < right {
res[left] = start
res[right] = -start
start++
left = left + 1
right = 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/0437.Path-Sum-III/437. Path Sum III_test.go | leetcode/0437.Path-Sum-III/437. Path Sum III_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question437 struct {
para437
ans437
}
// para 是参数
// one 代表第一个参数
type para437 struct {
one []int
sum int
}
// ans 是答案
// one 代表第一个答案
type ans437 struct {
one int
}
func Test_Problem437(t *testing.T) {
qs := []question437{
{
para437{[]int{}, 0},
ans437{0},
},
{
para437{[]int{10, 5, -3, 3, 2, structures.NULL, 11, 3, -2, structures.NULL, 1}, 8},
ans437{3},
},
}
fmt.Printf("------------------------Leetcode Problem 437------------------------\n")
for _, q := range qs {
_, p := q.ans437, q.para437
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 |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0437.Path-Sum-III/437. Path Sum III.go | leetcode/0437.Path-Sum-III/437. Path Sum III.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
* }
*/
// 解法一 带缓存 dfs
func pathSum(root *TreeNode, targetSum int) int {
prefixSum := make(map[int]int)
prefixSum[0] = 1
return dfs(root, prefixSum, 0, targetSum)
}
func dfs(root *TreeNode, prefixSum map[int]int, cur, sum int) int {
if root == nil {
return 0
}
cur += root.Val
cnt := 0
if v, ok := prefixSum[cur-sum]; ok {
cnt = v
}
prefixSum[cur]++
cnt += dfs(root.Left, prefixSum, cur, sum)
cnt += dfs(root.Right, prefixSum, cur, sum)
prefixSum[cur]--
return cnt
}
// 解法二
func pathSumIII(root *TreeNode, sum int) int {
if root == nil {
return 0
}
res := findPath437(root, sum)
res += pathSumIII(root.Left, sum)
res += pathSumIII(root.Right, sum)
return res
}
// 寻找包含 root 这个结点,且和为 sum 的路径
func findPath437(root *TreeNode, sum int) int {
if root == nil {
return 0
}
res := 0
if root.Val == sum {
res++
}
res += findPath437(root.Left, sum-root.Val)
res += findPath437(root.Right, sum-root.Val)
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/2183.Count-Array-Pairs-Divisible-by-K/2183. Count Array Pairs Divisible by K.go | leetcode/2183.Count-Array-Pairs-Divisible-by-K/2183. Count Array Pairs Divisible by K.go | package leetcode
import "math"
func countPairs(nums []int, k int) int64 {
n := int(math.Sqrt(float64(k)))
gcds, res := make(map[int]int, n), 0
for _, num := range nums {
gcds[gcd(num, k)]++
}
for a, n1 := range gcds {
for b, n2 := range gcds {
if a > b || (a*b)%k != 0 {
continue
}
if a != b {
res += n1 * n2
} else { // a == b
res += n1 * (n1 - 1) / 2
}
}
}
return int64(res)
}
func gcd(a, b int) int {
for a%b != 0 {
a, b = b, a%b
}
return b
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/2183.Count-Array-Pairs-Divisible-by-K/2183. Count Array Pairs Divisible by K_test.go | leetcode/2183.Count-Array-Pairs-Divisible-by-K/2183. Count Array Pairs Divisible by K_test.go | package leetcode
import (
"fmt"
"testing"
)
type question2182 struct {
para2182
ans2182
}
// para 是参数
// one 代表第一个参数
type para2182 struct {
nums []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans2182 struct {
one int64
}
func Test_Problem2182(t *testing.T) {
qs := []question2182{
{
para2182{[]int{1, 2, 3, 4, 5}, 2},
ans2182{7},
},
{
para2182{[]int{1, 2, 3, 4}, 5},
ans2182{0},
},
}
fmt.Printf("------------------------Leetcode Problem 2183------------------------\n")
for _, q := range qs {
_, p := q.ans2182, q.para2182
fmt.Printf("【input】:%v 【output】:%v\n", p, countPairs(p.nums, p.k))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0169.Majority-Element/169. Majority Element.go | leetcode/0169.Majority-Element/169. Majority Element.go | package leetcode
// 解法一 时间复杂度 O(n) 空间复杂度 O(1)
func majorityElement(nums []int) int {
res, count := nums[0], 0
for i := 0; i < len(nums); i++ {
if count == 0 {
res, count = nums[i], 1
} else {
if nums[i] == res {
count++
} else {
count--
}
}
}
return res
}
// 解法二 时间复杂度 O(n) 空间复杂度 O(n)
func majorityElement1(nums []int) int {
m := make(map[int]int)
for _, v := range nums {
m[v]++
if m[v] > len(nums)/2 {
return v
}
}
return 0
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0169.Majority-Element/169. Majority Element_test.go | leetcode/0169.Majority-Element/169. Majority Element_test.go | package leetcode
import (
"fmt"
"testing"
)
type question169 struct {
para169
ans169
}
// para 是参数
// one 代表第一个参数
type para169 struct {
s []int
}
// ans 是答案
// one 代表第一个答案
type ans169 struct {
one int
}
func Test_Problem169(t *testing.T) {
qs := []question169{
{
para169{[]int{2, 2, 1}},
ans169{2},
},
{
para169{[]int{3, 2, 3}},
ans169{3},
},
{
para169{[]int{2, 2, 1, 1, 1, 2, 2}},
ans169{2},
},
{
para169{[]int{-2147483648}},
ans169{-2147483648},
},
}
fmt.Printf("------------------------Leetcode Problem 169------------------------\n")
for _, q := range qs {
_, p := q.ans169, q.para169
fmt.Printf("【input】:%v 【output】:%v\n", p, majorityElement(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/0218.The-Skyline-Problem/218. The Skyline Problem_test.go | leetcode/0218.The-Skyline-Problem/218. The Skyline Problem_test.go | package leetcode
import (
"fmt"
"testing"
)
type question218 struct {
para218
ans218
}
// para 是参数
// one 代表第一个参数
type para218 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans218 struct {
one [][]int
}
func Test_Problem218(t *testing.T) {
qs := []question218{
{
para218{[][]int{{2, 9, 10}, {3, 7, 15}, {5, 12, 12}, {15, 20, 10}, {19, 24, 8}}},
ans218{[][]int{{2, 10}, {3, 15}, {7, 12}, {12, 0}, {15, 10}, {20, 8}, {24, 0}}},
},
{
para218{[][]int{{1, 2, 1}, {1, 2, 2}, {1, 2, 3}, {2, 3, 1}, {2, 3, 2}, {2, 3, 3}}},
ans218{[][]int{{1, 3}, {3, 0}}},
},
{
para218{[][]int{{4, 9, 10}, {4, 9, 15}, {4, 9, 12}, {10, 12, 10}, {10, 12, 8}}},
ans218{[][]int{{4, 15}, {9, 0}, {10, 10}, {12, 0}}},
},
}
fmt.Printf("------------------------Leetcode Problem 218------------------------\n")
for _, q := range qs {
_, p := q.ans218, q.para218
fmt.Printf("【input】:%v 【output】:%v\n", p, getSkyline(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/0218.The-Skyline-Problem/218. The Skyline Problem.go | leetcode/0218.The-Skyline-Problem/218. The Skyline Problem.go | package leetcode
import (
"sort"
"github.com/halfrost/LeetCode-Go/template"
)
// 解法一 树状数组,时间复杂度 O(n log n)
const LEFTSIDE = 1
const RIGHTSIDE = 2
type Point struct {
xAxis int
side int
index int
}
func getSkyline(buildings [][]int) [][]int {
res := [][]int{}
if len(buildings) == 0 {
return res
}
allPoints, bit := make([]Point, 0), BinaryIndexedTree{}
// [x-axis (value), [1 (left) | 2 (right)], index (building number)]
for i, b := range buildings {
allPoints = append(allPoints, Point{xAxis: b[0], side: LEFTSIDE, index: i})
allPoints = append(allPoints, Point{xAxis: b[1], side: RIGHTSIDE, index: i})
}
sort.Slice(allPoints, func(i, j int) bool {
if allPoints[i].xAxis == allPoints[j].xAxis {
return allPoints[i].side < allPoints[j].side
}
return allPoints[i].xAxis < allPoints[j].xAxis
})
bit.Init(len(allPoints))
kth := make(map[Point]int)
for i := 0; i < len(allPoints); i++ {
kth[allPoints[i]] = i
}
for i := 0; i < len(allPoints); i++ {
pt := allPoints[i]
if pt.side == LEFTSIDE {
bit.Add(kth[Point{xAxis: buildings[pt.index][1], side: RIGHTSIDE, index: pt.index}], buildings[pt.index][2])
}
currHeight := bit.Query(kth[pt] + 1)
if len(res) == 0 || res[len(res)-1][1] != currHeight {
if len(res) > 0 && res[len(res)-1][0] == pt.xAxis {
res[len(res)-1][1] = currHeight
} else {
res = append(res, []int{pt.xAxis, currHeight})
}
}
}
return res
}
type BinaryIndexedTree struct {
tree []int
capacity int
}
// Init define
func (bit *BinaryIndexedTree) Init(capacity int) {
bit.tree, bit.capacity = make([]int, capacity+1), capacity
}
// Add define
func (bit *BinaryIndexedTree) Add(index int, val int) {
for ; index > 0; index -= index & -index {
bit.tree[index] = max(bit.tree[index], val)
}
}
// Query define
func (bit *BinaryIndexedTree) Query(index int) int {
sum := 0
for ; index <= bit.capacity; index += index & -index {
sum = max(sum, bit.tree[index])
}
return sum
}
// 解法二 线段树 Segment Tree,时间复杂度 O(n log n)
func getSkyline1(buildings [][]int) [][]int {
st, ans, lastHeight, check := template.SegmentTree{}, [][]int{}, 0, false
posMap, pos := discretization218(buildings)
tmp := make([]int, len(posMap))
st.Init(tmp, func(i, j int) int {
return max(i, j)
})
for _, b := range buildings {
st.UpdateLazy(posMap[b[0]], posMap[b[1]-1], b[2])
}
for i := 0; i < len(pos); i++ {
h := st.QueryLazy(posMap[pos[i]], posMap[pos[i]])
if check == false && h != 0 {
ans = append(ans, []int{pos[i], h})
check = true
} else if i > 0 && h != lastHeight {
ans = append(ans, []int{pos[i], h})
}
lastHeight = h
}
return ans
}
func discretization218(positions [][]int) (map[int]int, []int) {
tmpMap, posArray, posMap := map[int]int{}, []int{}, map[int]int{}
for _, pos := range positions {
tmpMap[pos[0]]++
tmpMap[pos[1]-1]++
tmpMap[pos[1]]++
}
for k := range tmpMap {
posArray = append(posArray, k)
}
sort.Ints(posArray)
for i, pos := range posArray {
posMap[pos] = i
}
return posMap, posArray
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
// 解法三 扫描线 Sweep Line,时间复杂度 O(n log n)
func getSkyline2(buildings [][]int) [][]int {
size := len(buildings)
es := make([]E, 0)
for i, b := range buildings {
l := b[0]
r := b[1]
h := b[2]
// 1-- enter
el := NewE(i, l, h, 0)
es = append(es, el)
// 0 -- leave
er := NewE(i, r, h, 1)
es = append(es, er)
}
skyline := make([][]int, 0)
sort.Slice(es, func(i, j int) bool {
if es[i].X == es[j].X {
if es[i].T == es[j].T {
if es[i].T == 0 {
return es[i].H > es[j].H
}
return es[i].H < es[j].H
}
return es[i].T < es[j].T
}
return es[i].X < es[j].X
})
pq := NewIndexMaxPQ(size)
for _, e := range es {
curH := pq.Front()
if e.T == 0 {
if e.H > curH {
skyline = append(skyline, []int{e.X, e.H})
}
pq.Enque(e.N, e.H)
} else {
pq.Remove(e.N)
h := pq.Front()
if curH > h {
skyline = append(skyline, []int{e.X, h})
}
}
}
return skyline
}
// 扫面线伪代码
// events = {{x: L , height: H , type: entering},
// {x: R , height: H , type: leaving}}
// event.SortByX()
// ds = new DS()
// for e in events:
// if entering(e):
// if e.height > ds.max(): ans += [e.height]
// ds.add(e.height)
// if leaving(e):
// ds.remove(e.height)
// if e.height > ds.max(): ans += [ds.max()]
// E define
type E struct { // 定义一个 event 事件
N int // number 编号
X int // x 坐标
H int // height 高度
T int // type 0-进入 1-离开
}
// NewE define
func NewE(n, x, h, t int) E {
return E{
N: n,
X: x,
H: h,
T: t,
}
}
// IndexMaxPQ define
type IndexMaxPQ struct {
items []int
pq []int
qp []int
total int
}
// NewIndexMaxPQ define
func NewIndexMaxPQ(n int) IndexMaxPQ {
qp := make([]int, n)
for i := 0; i < n; i++ {
qp[i] = -1
}
return IndexMaxPQ{
items: make([]int, n),
pq: make([]int, n+1),
qp: qp,
}
}
// Enque define
func (q *IndexMaxPQ) Enque(key, val int) {
q.total++
q.items[key] = val
q.pq[q.total] = key
q.qp[key] = q.total
q.swim(q.total)
}
// Front define
func (q *IndexMaxPQ) Front() int {
if q.total < 1 {
return 0
}
return q.items[q.pq[1]]
}
// Remove define
func (q *IndexMaxPQ) Remove(key int) {
rank := q.qp[key]
q.exch(rank, q.total)
q.total--
q.qp[key] = -1
q.sink(rank)
}
func (q *IndexMaxPQ) sink(n int) {
for 2*n <= q.total {
k := 2 * n
if k < q.total && q.less(k, k+1) {
k++
}
if q.less(k, n) {
break
}
q.exch(k, n)
n = k
}
}
func (q *IndexMaxPQ) swim(n int) {
for n > 1 {
k := n / 2
if q.less(n, k) {
break
}
q.exch(n, k)
n = k
}
}
func (q *IndexMaxPQ) exch(i, j int) {
q.pq[i], q.pq[j] = q.pq[j], q.pq[i]
q.qp[q.pq[i]] = i
q.qp[q.pq[j]] = j
}
func (q *IndexMaxPQ) less(i, j int) bool {
return q.items[q.pq[i]] < q.items[q.pq[j]]
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0017.Letter-Combinations-of-a-Phone-Number/17. Letter Combinations of a Phone Number_test.go | leetcode/0017.Letter-Combinations-of-a-Phone-Number/17. Letter Combinations of a Phone Number_test.go | package leetcode
import (
"fmt"
"testing"
)
type question17 struct {
para17
ans17
}
// para 是参数
// one 代表第一个参数
type para17 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans17 struct {
one []string
}
func Test_Problem17(t *testing.T) {
qs := []question17{
{
para17{"23"},
ans17{[]string{"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"}},
},
}
fmt.Printf("------------------------Leetcode Problem 17------------------------\n")
for _, q := range qs {
_, p := q.ans17, q.para17
fmt.Printf("【input】:%v 【output】:%v\n", p, letterCombinations(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/0017.Letter-Combinations-of-a-Phone-Number/17. Letter Combinations of a Phone Number.go | leetcode/0017.Letter-Combinations-of-a-Phone-Number/17. Letter Combinations of a Phone Number.go | package leetcode
var (
letterMap = []string{
" ", //0
"", //1
"abc", //2
"def", //3
"ghi", //4
"jkl", //5
"mno", //6
"pqrs", //7
"tuv", //8
"wxyz", //9
}
res = []string{}
final = 0
)
// 解法一 DFS
func letterCombinations(digits string) []string {
if digits == "" {
return []string{}
}
res = []string{}
findCombination(&digits, 0, "")
return res
}
func findCombination(digits *string, index int, s string) {
if index == len(*digits) {
res = append(res, s)
return
}
num := (*digits)[index]
letter := letterMap[num-'0']
for i := 0; i < len(letter); i++ {
findCombination(digits, index+1, s+string(letter[i]))
}
return
}
// 解法二 非递归
func letterCombinations_(digits string) []string {
if digits == "" {
return []string{}
}
index := digits[0] - '0'
letter := letterMap[index]
tmp := []string{}
for i := 0; i < len(letter); i++ {
if len(res) == 0 {
res = append(res, "")
}
for j := 0; j < len(res); j++ {
tmp = append(tmp, res[j]+string(letter[i]))
}
}
res = tmp
final++
letterCombinations(digits[1:])
final--
if final == 0 {
tmp = res
res = []string{}
}
return tmp
}
// 解法三 回溯(参考回溯模板,类似DFS)
var result []string
var dict = map[string][]string{
"2": {"a", "b", "c"},
"3": {"d", "e", "f"},
"4": {"g", "h", "i"},
"5": {"j", "k", "l"},
"6": {"m", "n", "o"},
"7": {"p", "q", "r", "s"},
"8": {"t", "u", "v"},
"9": {"w", "x", "y", "z"},
}
func letterCombinationsBT(digits string) []string {
result = []string{}
if digits == "" {
return result
}
letterFunc("", digits)
return result
}
func letterFunc(res string, digits string) {
if digits == "" {
result = append(result, res)
return
}
k := digits[0:1]
digits = digits[1:]
for i := 0; i < len(dict[k]); i++ {
res += dict[k][i]
letterFunc(res, digits)
res = res[0 : len(res)-1]
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1653.Minimum-Deletions-to-Make-String-Balanced/1653. Minimum Deletions to Make String Balanced_test.go | leetcode/1653.Minimum-Deletions-to-Make-String-Balanced/1653. Minimum Deletions to Make String Balanced_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1653 struct {
para1653
ans1653
}
// para 是参数
// one 代表第一个参数
type para1653 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans1653 struct {
one int
}
func Test_Problem1653(t *testing.T) {
qs := []question1653{
{
para1653{"aababbab"},
ans1653{2},
},
{
para1653{"bbaaaaabb"},
ans1653{2},
},
{
para1653{"b"},
ans1653{0},
},
{
para1653{"ababaaaabbbbbaaababbbbbbaaabbaababbabbbbaabbbbaabbabbabaabbbababaa"},
ans1653{25},
},
}
fmt.Printf("------------------------Leetcode Problem 1653------------------------\n")
for _, q := range qs {
_, p := q.ans1653, q.para1653
fmt.Printf("【input】:%v 【output】:%v \n", p, minimumDeletions(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/1653.Minimum-Deletions-to-Make-String-Balanced/1653. Minimum Deletions to Make String Balanced.go | leetcode/1653.Minimum-Deletions-to-Make-String-Balanced/1653. Minimum Deletions to Make String Balanced.go | package leetcode
// 解法一 DP
func minimumDeletions(s string) int {
prev, res, bCount := 0, 0, 0
for _, c := range s {
if c == 'a' {
res = min(prev+1, bCount)
prev = res
} else {
bCount++
}
}
return res
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// 解法二 模拟
func minimumDeletions1(s string) int {
aCount, bCount, res := 0, 0, 0
for i := 0; i < len(s); i++ {
if s[i] == 'a' {
aCount++
}
}
res = aCount
for i := 0; i < len(s); i++ {
if s[i] == 'a' {
aCount--
} else {
bCount++
}
res = min(res, aCount+bCount)
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0290.Word-Pattern/290. Word Pattern.go | leetcode/0290.Word-Pattern/290. Word Pattern.go | package leetcode
import "strings"
func wordPattern(pattern string, str string) bool {
strList := strings.Split(str, " ")
patternByte := []byte(pattern)
if pattern == "" || len(patternByte) != len(strList) {
return false
}
pMap := map[byte]string{}
sMap := map[string]byte{}
for index, b := range patternByte {
if _, ok := pMap[b]; !ok {
if _, ok = sMap[strList[index]]; !ok {
pMap[b] = strList[index]
sMap[strList[index]] = b
} else {
if sMap[strList[index]] != b {
return false
}
}
} else {
if pMap[b] != strList[index] {
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/0290.Word-Pattern/290. Word Pattern_test.go | leetcode/0290.Word-Pattern/290. Word Pattern_test.go | package leetcode
import (
"fmt"
"testing"
)
type question290 struct {
para290
ans290
}
// para 是参数
// one 代表第一个参数
type para290 struct {
one string
two string
}
// ans 是答案
// one 代表第一个答案
type ans290 struct {
one bool
}
func Test_Problem290(t *testing.T) {
qs := []question290{
{
para290{"abba", "dog cat cat dog"},
ans290{true},
},
{
para290{"abba", "dog cat cat fish"},
ans290{false},
},
{
para290{"aaaa", "dog cat cat dog"},
ans290{false},
},
{
para290{"abba", "dog dog dog dog"},
ans290{false},
},
}
fmt.Printf("------------------------Leetcode Problem 290------------------------\n")
for _, q := range qs {
_, p := q.ans290, q.para290
fmt.Printf("【input】:%v 【output】:%v\n", p, wordPattern(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/0392.Is-Subsequence/392. Is Subsequence.go | leetcode/0392.Is-Subsequence/392. Is Subsequence.go | package leetcode
// 解法一 O(n^2)
func isSubsequence(s string, t string) bool {
index := 0
for i := 0; i < len(s); i++ {
flag := false
for ; index < len(t); index++ {
if s[i] == t[index] {
flag = true
break
}
}
if flag == true {
index++
continue
} else {
return false
}
}
return true
}
// 解法二 O(n)
func isSubsequence1(s string, t string) bool {
for len(s) > 0 && len(t) > 0 {
if s[0] == t[0] {
s = s[1:]
}
t = t[1:]
}
return len(s) == 0
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0392.Is-Subsequence/392. Is Subsequence_test.go | leetcode/0392.Is-Subsequence/392. Is Subsequence_test.go | package leetcode
import (
"fmt"
"testing"
)
type question392 struct {
para392
ans392
}
// para 是参数
// one 代表第一个参数
type para392 struct {
one string
two string
}
// ans 是答案
// one 代表第一个答案
type ans392 struct {
one bool
}
func Test_Problem392(t *testing.T)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yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyeyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"},
ans392{false},
},
}
fmt.Printf("------------------------Leetcode Problem 392------------------------\n")
for _, q := range qs {
_, p := q.ans392, q.para392
fmt.Printf("【input】:%v 【output】:%v\n", p, isSubsequence(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/0390.Elimination-Game/390. Elimination Game_test.go | leetcode/0390.Elimination-Game/390. Elimination Game_test.go | package leetcode
import (
"fmt"
"testing"
)
type question390 struct {
para390
ans390
}
// para 是参数
// one 代表第一个参数
type para390 struct {
n int
}
// ans 是答案
// one 代表第一个答案
type ans390 struct {
one int
}
func Test_Problem390(t *testing.T) {
qs := []question390{
{
para390{9},
ans390{6},
},
{
para390{1},
ans390{1},
},
}
fmt.Printf("------------------------Leetcode Problem 390------------------------\n")
for _, q := range qs {
_, p := q.ans390, q.para390
fmt.Printf("【input】:%v 【output】:%v\n", p, lastRemaining(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/0390.Elimination-Game/390. Elimination Game.go | leetcode/0390.Elimination-Game/390. Elimination Game.go | package leetcode
func lastRemaining(n int) int {
start, dir, step := 1, true, 1
for n > 1 {
if dir { // 正向
start += step
} else { // 反向
if n%2 == 1 {
start += step
}
}
dir = !dir
n >>= 1
step <<= 1
}
return start
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0341.Flatten-Nested-List-Iterator/341. Flatten Nested List Iterator.go | leetcode/0341.Flatten-Nested-List-Iterator/341. Flatten Nested List Iterator.go | package leetcode
import "container/list"
// This is the interface that allows for creating nested lists.
// You should not implement it, or speculate about its implementation
type NestedInteger struct {
}
// Return true if this NestedInteger holds a single integer, rather than a nested list.
func (this NestedInteger) IsInteger() bool { return true }
// Return the single integer that this NestedInteger holds, if it holds a single integer
// The result is undefined if this NestedInteger holds a nested list
// So before calling this method, you should have a check
func (this NestedInteger) GetInteger() int { return 0 }
// Set this NestedInteger to hold a single integer.
func (n *NestedInteger) SetInteger(value int) {}
// Set this NestedInteger to hold a nested list and adds a nested integer to it.
func (this *NestedInteger) Add(elem NestedInteger) {}
// Return the nested list that this NestedInteger holds, if it holds a nested list
// The list length is zero if this NestedInteger holds a single integer
// You can access NestedInteger's List element directly if you want to modify it
func (this NestedInteger) GetList() []*NestedInteger { return nil }
type NestedIterator struct {
stack *list.List
}
type listIndex struct {
nestedList []*NestedInteger
index int
}
func Constructor(nestedList []*NestedInteger) *NestedIterator {
stack := list.New()
stack.PushBack(&listIndex{nestedList, 0})
return &NestedIterator{stack}
}
func (this *NestedIterator) Next() int {
if !this.HasNext() {
return -1
}
last := this.stack.Back().Value.(*listIndex)
nestedList, i := last.nestedList, last.index
val := nestedList[i].GetInteger()
last.index++
return val
}
func (this *NestedIterator) HasNext() bool {
stack := this.stack
for stack.Len() > 0 {
last := stack.Back().Value.(*listIndex)
nestedList, i := last.nestedList, last.index
if i >= len(nestedList) {
stack.Remove(stack.Back())
} else {
val := nestedList[i]
if val.IsInteger() {
return true
}
last.index++
stack.PushBack(&listIndex{val.GetList(), 0})
}
}
return false
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0341.Flatten-Nested-List-Iterator/341. Flatten Nested List Iterator_test.go | leetcode/0341.Flatten-Nested-List-Iterator/341. Flatten Nested List Iterator_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem338(t *testing.T) {
obj := Constructor([]*NestedInteger{})
fmt.Printf("obj = %v\n", obj)
fmt.Printf("obj = %v\n", obj.Next())
fmt.Printf("obj = %v\n", obj.HasNext())
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1742.Maximum-Number-of-Balls-in-a-Box/1742. Maximum Number of Balls in a Box.go | leetcode/1742.Maximum-Number-of-Balls-in-a-Box/1742. Maximum Number of Balls in a Box.go | package leetcode
func countBalls(lowLimit int, highLimit int) int {
buckets, maxBall := [46]int{}, 0
for i := lowLimit; i <= highLimit; i++ {
t := 0
for j := i; j > 0; {
t += j % 10
j = j / 10
}
buckets[t]++
if buckets[t] > maxBall {
maxBall = buckets[t]
}
}
return maxBall
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1742.Maximum-Number-of-Balls-in-a-Box/1742. Maximum Number of Balls in a Box_test.go | leetcode/1742.Maximum-Number-of-Balls-in-a-Box/1742. Maximum Number of Balls in a Box_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1742 struct {
para1742
ans1742
}
// para 是参数
// one 代表第一个参数
type para1742 struct {
lowLimit int
highLimit int
}
// ans 是答案
// one 代表第一个答案
type ans1742 struct {
one int
}
func Test_Problem1742(t *testing.T) {
qs := []question1742{
{
para1742{1, 10},
ans1742{2},
},
{
para1742{5, 15},
ans1742{2},
},
{
para1742{19, 28},
ans1742{2},
},
}
fmt.Printf("------------------------Leetcode Problem 1742------------------------\n")
for _, q := range qs {
_, p := q.ans1742, q.para1742
fmt.Printf("【input】:%v 【output】:%v\n", p, countBalls(p.lowLimit, p.highLimit))
}
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/1317.Convert-Integer-to-the-Sum-of-Two-No-Zero-Integers/1317. Convert Integer to the Sum of Two No-Zero Integers_test.go | leetcode/1317.Convert-Integer-to-the-Sum-of-Two-No-Zero-Integers/1317. Convert Integer to the Sum of Two No-Zero Integers_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1317 struct {
para1317
ans1317
}
// para 是参数
// one 代表第一个参数
type para1317 struct {
one int
}
// ans 是答案
// one 代表第一个答案
type ans1317 struct {
one []int
}
func Test_Problem1317(t *testing.T) {
qs := []question1317{
{
para1317{5},
ans1317{[]int{1, 4}},
},
{
para1317{0},
ans1317{[]int{}},
},
{
para1317{3},
ans1317{[]int{1, 2}},
},
{
para1317{1},
ans1317{[]int{}},
},
{
para1317{2},
ans1317{[]int{1, 1}},
},
{
para1317{11},
ans1317{[]int{2, 9}},
},
{
para1317{10000},
ans1317{[]int{1, 9999}},
},
{
para1317{69},
ans1317{[]int{1, 68}},
},
{
para1317{1010},
ans1317{[]int{11, 999}},
},
}
fmt.Printf("------------------------Leetcode Problem 1317------------------------\n")
for _, q := range qs {
_, p := q.ans1317, q.para1317
fmt.Printf("【input】:%v 【output】:%v\n", p, getNoZeroIntegers(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/1317.Convert-Integer-to-the-Sum-of-Two-No-Zero-Integers/1317. Convert Integer to the Sum of Two No-Zero Integers.go | leetcode/1317.Convert-Integer-to-the-Sum-of-Two-No-Zero-Integers/1317. Convert Integer to the Sum of Two No-Zero Integers.go | package leetcode
func getNoZeroIntegers(n int) []int {
noZeroPair := []int{}
for i := 1; i <= n/2; i++ {
if isNoZero(i) && isNoZero(n-i) {
noZeroPair = append(noZeroPair, []int{i, n - i}...)
break
}
}
return noZeroPair
}
func isNoZero(n int) bool {
for n != 0 {
if n%10 == 0 {
return false
}
n /= 10
}
return true
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0674.Longest-Continuous-Increasing-Subsequence/674. Longest Continuous Increasing Subsequence.go | leetcode/0674.Longest-Continuous-Increasing-Subsequence/674. Longest Continuous Increasing Subsequence.go | package leetcode
func findLengthOfLCIS(nums []int) int {
if len(nums) == 0 {
return 0
}
res, length := 1, 1
for i := 1; i < len(nums); i++ {
if nums[i] > nums[i-1] {
length++
} else {
res = max(res, length)
length = 1
}
}
return max(res, length)
}
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/0674.Longest-Continuous-Increasing-Subsequence/674. Longest Continuous Increasing Subsequence_test.go | leetcode/0674.Longest-Continuous-Increasing-Subsequence/674. Longest Continuous Increasing Subsequence_test.go | package leetcode
import (
"fmt"
"testing"
)
type question674 struct {
para674
ans674
}
// para 是参数
// one 代表第一个参数
type para674 struct {
nums []int
}
// ans 是答案
// one 代表第一个答案
type ans674 struct {
one int
}
func Test_Problem674(t *testing.T) {
qs := []question674{
{
para674{[]int{1, 3, 5, 4, 7}},
ans674{3},
},
{
para674{[]int{2, 2, 2, 2, 2}},
ans674{1},
},
{
para674{[]int{1, 3, 5, 7}},
ans674{4},
},
}
fmt.Printf("------------------------Leetcode Problem 674------------------------\n")
for _, q := range qs {
_, p := q.ans674, q.para674
fmt.Printf("【input】:%v 【output】:%v\n", p, findLengthOfLCIS(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/0961.N-Repeated-Element-in-Size-2N-Array/961. N-Repeated Element in Size 2N Array.go | leetcode/0961.N-Repeated-Element-in-Size-2N-Array/961. N-Repeated Element in Size 2N Array.go | package leetcode
func repeatedNTimes(A []int) int {
kv := make(map[int]struct{})
for _, val := range A {
if _, ok := kv[val]; ok {
return val
}
kv[val] = struct{}{}
}
return 0
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0961.N-Repeated-Element-in-Size-2N-Array/961. N-Repeated Element in Size 2N Array_test.go | leetcode/0961.N-Repeated-Element-in-Size-2N-Array/961. N-Repeated Element in Size 2N Array_test.go | package leetcode
import (
"fmt"
"testing"
)
type question961 struct {
para961
ans961
}
// para 是参数
// one 代表第一个参数
type para961 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans961 struct {
one int
}
func Test_Problem961(t *testing.T) {
qs := []question961{
{
para961{[]int{1, 2, 3, 3}},
ans961{3},
},
{
para961{[]int{2, 1, 2, 5, 3, 2}},
ans961{2},
},
{
para961{[]int{5, 1, 5, 2, 5, 3, 5, 4}},
ans961{5},
},
}
fmt.Printf("------------------------Leetcode Problem 961------------------------\n")
for _, q := range qs {
_, p := q.ans961, q.para961
fmt.Printf("【input】:%v 【output】:%v\n", p, repeatedNTimes(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/1734.Decode-XORed-Permutation/1734. Decode XORed Permutation_test.go | leetcode/1734.Decode-XORed-Permutation/1734. Decode XORed Permutation_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1734 struct {
para1734
ans1734
}
// para 是参数
// one 代表第一个参数
type para1734 struct {
encoded []int
}
// ans 是答案
// one 代表第一个答案
type ans1734 struct {
one []int
}
func Test_Problem1734(t *testing.T) {
qs := []question1734{
{
para1734{[]int{3, 1}},
ans1734{[]int{1, 2, 3}},
},
{
para1734{[]int{6, 5, 4, 6}},
ans1734{[]int{2, 4, 1, 5, 3}},
},
}
fmt.Printf("------------------------Leetcode Problem 1734------------------------\n")
for _, q := range qs {
_, p := q.ans1734, q.para1734
fmt.Printf("【input】:%v 【output】:%v\n", p, decode(p.encoded))
}
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/1734.Decode-XORed-Permutation/1734. Decode XORed Permutation.go | leetcode/1734.Decode-XORed-Permutation/1734. Decode XORed Permutation.go | package leetcode
func decode(encoded []int) []int {
n, total, odd := len(encoded), 0, 0
for i := 1; i <= n+1; i++ {
total ^= i
}
for i := 1; i < n; i += 2 {
odd ^= encoded[i]
}
perm := make([]int, n+1)
perm[0] = total ^ odd
for i, v := range encoded {
perm[i+1] = perm[i] ^ v
}
return perm
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1482.Minimum-Number-of-Days-to-Make-m-Bouquets/1482. Minimum Number of Days to Make m Bouquets_test.go | leetcode/1482.Minimum-Number-of-Days-to-Make-m-Bouquets/1482. Minimum Number of Days to Make m Bouquets_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1482 struct {
para1482
ans1482
}
// para 是参数
// one 代表第一个参数
type para1482 struct {
bloomDay []int
m int
k int
}
// ans 是答案
// one 代表第一个答案
type ans1482 struct {
one int
}
func Test_Problem1482(t *testing.T) {
qs := []question1482{
{
para1482{[]int{1, 10, 3, 10, 2}, 3, 1},
ans1482{3},
},
{
para1482{[]int{1, 10, 3, 10, 2}, 3, 2},
ans1482{-1},
},
{
para1482{[]int{7, 7, 7, 7, 12, 7, 7}, 2, 3},
ans1482{12},
},
{
para1482{[]int{1000000000, 1000000000}, 1, 1},
ans1482{1000000000},
},
{
para1482{[]int{1, 10, 2, 9, 3, 8, 4, 7, 5, 6}, 4, 2},
ans1482{9},
},
}
fmt.Printf("------------------------Leetcode Problem 1482------------------------\n")
for _, q := range qs {
_, p := q.ans1482, q.para1482
fmt.Printf("【input】:%v 【output】:%v \n", p, minDays(p.bloomDay, p.m, 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/1482.Minimum-Number-of-Days-to-Make-m-Bouquets/1482. Minimum Number of Days to Make m Bouquets.go | leetcode/1482.Minimum-Number-of-Days-to-Make-m-Bouquets/1482. Minimum Number of Days to Make m Bouquets.go | package leetcode
import "sort"
func minDays(bloomDay []int, m int, k int) int {
if m*k > len(bloomDay) {
return -1
}
maxDay := 0
for _, day := range bloomDay {
if day > maxDay {
maxDay = day
}
}
return sort.Search(maxDay, func(days int) bool {
flowers, bouquets := 0, 0
for _, d := range bloomDay {
if d > days {
flowers = 0
} else {
flowers++
if flowers == k {
bouquets++
flowers = 0
}
}
}
return bouquets >= m
})
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1022.Sum-of-Root-To-Leaf-Binary-Numbers/1022. Sum of Root To Leaf Binary Numbers.go | leetcode/1022.Sum-of-Root-To-Leaf-Binary-Numbers/1022. Sum of Root To Leaf Binary Numbers.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 sumRootToLeaf(root *TreeNode) int {
var dfs func(*TreeNode, int) int
dfs = func(node *TreeNode, sum int) int {
if node == nil {
return 0
}
sum = sum<<1 | node.Val
// 上一行也可以写作 sum = sum*2 + node.Val
if node.Left == nil && node.Right == nil {
return sum
}
return dfs(node.Left, sum) + dfs(node.Right, sum)
}
return dfs(root, 0)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1022.Sum-of-Root-To-Leaf-Binary-Numbers/1022. Sum of Root To Leaf Binary Numbers_test.go | leetcode/1022.Sum-of-Root-To-Leaf-Binary-Numbers/1022. Sum of Root To Leaf Binary Numbers_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question1022 struct {
para1022
ans1022
}
// para 是参数
// one 代表第一个参数
type para1022 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans1022 struct {
one int
}
func Test_Problem1022(t *testing.T) {
qs := []question1022{
{
para1022{[]int{1, 0, 1, 0, 1, 0, 1}},
ans1022{22},
},
{
para1022{[]int{0}},
ans1022{0},
},
}
fmt.Printf("------------------------Leetcode Problem 1022------------------------\n")
for _, q := range qs {
_, p := q.ans1022, q.para1022
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【input】:%v 【output】:%v\n", p, sumRootToLeaf(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/0237.Delete-Node-in-a-Linked-List/237. Delete Node in a Linked List_test.go | leetcode/0237.Delete-Node-in-a-Linked-List/237. Delete Node in a Linked List_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question237 struct {
para237
ans237
}
// para 是参数
// one 代表第一个参数
type para237 struct {
one []int
n int
}
// ans 是答案
// one 代表第一个答案
type ans237 struct {
one []int
}
func Test_Problem237(t *testing.T) {
qs := []question237{
{
para237{[]int{1, 2, 3, 4, 5}, 1},
ans237{[]int{2, 3, 4, 5}},
},
{
para237{[]int{1, 2, 3, 4, 5}, 2},
ans237{[]int{1, 3, 4, 5}},
},
{
para237{[]int{1, 1, 1, 1, 1}, 1},
ans237{[]int{}},
},
{
para237{[]int{1, 2, 3, 4, 5}, 5},
ans237{[]int{1, 2, 3, 4}},
},
{
para237{[]int{}, 5},
ans237{[]int{}},
},
{
para237{[]int{1, 2, 3, 4, 5}, 10},
ans237{[]int{1, 2, 3, 4, 5}},
},
{
para237{[]int{1}, 1},
ans237{[]int{}},
},
}
fmt.Printf("------------------------Leetcode Problem 237------------------------\n")
for _, q := range qs {
_, p := q.ans237, q.para237
fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(removeElements(structures.Ints2List(p.one), p.n)))
}
fmt.Printf("\n\n\n")
}
func removeElements(head *ListNode, val int) *ListNode {
if head == nil {
return head
}
newHead := &ListNode{Val: 0, Next: head}
pre := newHead
cur := head
for cur != nil {
if cur.Val == val {
pre.Next = cur.Next
} else {
pre = cur
}
cur = cur.Next
}
return newHead.Next
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0237.Delete-Node-in-a-Linked-List/237. Delete Node in a Linked List.go | leetcode/0237.Delete-Node-in-a-Linked-List/237. Delete Node in a Linked List.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// ListNode define
type ListNode = structures.ListNode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteNode(node *ListNode) {
node.Val = node.Next.Val
node.Next = node.Next.Next
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0647.Palindromic-Substrings/647. Palindromic Substrings_test.go | leetcode/0647.Palindromic-Substrings/647. Palindromic Substrings_test.go | package leetcode
import (
"fmt"
"testing"
)
type question647 struct {
para647
ans647
}
// para 是参数
// one 代表第一个参数
type para647 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans647 struct {
one int
}
func Test_Problem647(t *testing.T) {
qs := []question647{
{
para647{"abc"},
ans647{3},
},
{
para647{"aaa"},
ans647{6},
},
}
fmt.Printf("------------------------Leetcode Problem 647------------------------\n")
for _, q := range qs {
_, p := q.ans647, q.para647
fmt.Printf("【input】:%v 【output】:%v\n", p, countSubstrings(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/0647.Palindromic-Substrings/647. Palindromic Substrings.go | leetcode/0647.Palindromic-Substrings/647. Palindromic Substrings.go | package leetcode
func countSubstrings(s string) int {
res := 0
for i := 0; i < len(s); i++ {
res += countPalindrome(s, i, i)
res += countPalindrome(s, i, i+1)
}
return res
}
func countPalindrome(s string, left, right int) int {
res := 0
for left >= 0 && right < len(s) {
if s[left] != s[right] {
break
}
left--
right++
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/1026.Maximum-Difference-Between-Node-and-Ancestor/1026. Maximum Difference Between Node and Ancestor.go | leetcode/1026.Maximum-Difference-Between-Node-and-Ancestor/1026. Maximum Difference Between Node and Ancestor.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 maxAncestorDiff(root *TreeNode) int {
res := 0
dfsAncestorDiff(root, &res)
return res
}
func dfsAncestorDiff(root *TreeNode, res *int) (int, int) {
if root == nil {
return -1, -1
}
leftMax, leftMin := dfsAncestorDiff(root.Left, res)
if leftMax == -1 && leftMin == -1 {
leftMax = root.Val
leftMin = root.Val
}
rightMax, rightMin := dfsAncestorDiff(root.Right, res)
if rightMax == -1 && rightMin == -1 {
rightMax = root.Val
rightMin = root.Val
}
*res = max(*res, max(abs(root.Val-min(leftMin, rightMin)), abs(root.Val-max(leftMax, rightMax))))
return max(leftMax, max(rightMax, root.Val)), min(leftMin, min(rightMin, root.Val))
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
func min(a int, b int) int {
if a > b {
return b
}
return a
}
func abs(a int) int {
if a > 0 {
return a
}
return -a
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1026.Maximum-Difference-Between-Node-and-Ancestor/1026. Maximum Difference Between Node and Ancestor_test.go | leetcode/1026.Maximum-Difference-Between-Node-and-Ancestor/1026. Maximum Difference Between Node and Ancestor_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question1026 struct {
para1026
ans1026
}
// para 是参数
// one 代表第一个参数
type para1026 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans1026 struct {
one int
}
func Test_Problem1026(t *testing.T) {
qs := []question1026{
{
para1026{[]int{}},
ans1026{0},
},
{
para1026{[]int{8, 3, 10, 1, 6, structures.NULL, 14, structures.NULL, structures.NULL, 4, 7, 13}},
ans1026{7},
},
{
para1026{[]int{7, 6, 4, 3, 1}},
ans1026{6},
},
{
para1026{[]int{1, 3, 2, 8, 4, 9}},
ans1026{8},
},
}
fmt.Printf("------------------------Leetcode Problem 1026------------------------\n")
for _, q := range qs {
_, p := q.ans1026, q.para1026
tree := structures.Ints2TreeNode(p.one)
fmt.Printf("【input】:%v 【output】:%v\n", p, maxAncestorDiff(tree))
}
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/0322.Coin-Change/322. Coin Change_test.go | leetcode/0322.Coin-Change/322. Coin Change_test.go | package leetcode
import (
"fmt"
"testing"
)
type question322 struct {
para322
ans322
}
// para 是参数
// one 代表第一个参数
type para322 struct {
one []int
amount int
}
// ans 是答案
// one 代表第一个答案
type ans322 struct {
one int
}
func Test_Problem322(t *testing.T) {
qs := []question322{
{
para322{[]int{186, 419, 83, 408}, 6249},
ans322{20},
},
{
para322{[]int{1, 2147483647}, 2},
ans322{2},
},
{
para322{[]int{1, 2, 5}, 11},
ans322{3},
},
{
para322{[]int{2}, 3},
ans322{-1},
},
{
para322{[]int{1}, 0},
ans322{0},
},
}
fmt.Printf("------------------------Leetcode Problem 322------------------------\n")
for _, q := range qs {
_, p := q.ans322, q.para322
fmt.Printf("【input】:%v 【output】:%v\n", p, coinChange(p.one, p.amount))
}
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/0322.Coin-Change/322. Coin Change.go | leetcode/0322.Coin-Change/322. Coin Change.go | package leetcode
func coinChange(coins []int, amount int) int {
dp := make([]int, amount+1)
dp[0] = 0
for i := 1; i < len(dp); i++ {
dp[i] = amount + 1
}
for i := 1; i <= amount; i++ {
for j := 0; j < len(coins); j++ {
if coins[j] <= i {
dp[i] = min(dp[i], dp[i-coins[j]]+1)
}
}
}
if dp[amount] > amount {
return -1
}
return dp[amount]
}
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/0118.Pascals-Triangle/118. Pascals Triangle_test.go | leetcode/0118.Pascals-Triangle/118. Pascals Triangle_test.go | package leetcode
import (
"fmt"
"testing"
)
type question118 struct {
para118
ans118
}
// para 是参数
// one 代表第一个参数
type para118 struct {
numRows int
}
// ans 是答案
// one 代表第一个答案
type ans118 struct {
one [][]int
}
func Test_Problem118(t *testing.T) {
qs := []question118{
{
para118{2},
ans118{[][]int{{1}, {1, 1}}},
},
{
para118{5},
ans118{[][]int{{1}, {1, 1}, {1, 2, 1}, {1, 3, 3, 1}, {1, 4, 6, 4, 1}}},
},
{
para118{10},
ans118{[][]int{{1}, {1, 1}, {1, 2, 1}, {1, 3, 3, 1}, {1, 4, 6, 4, 1}, {1, 5, 10, 10, 5, 1}, {1, 6, 15, 20, 15, 6, 1}, {1, 7, 21, 35, 35, 21, 7, 1}, {1, 8, 28, 56, 70, 56, 28, 8, 1}, {1, 9, 36, 84, 126, 126, 84, 36, 9, 1}}},
},
}
fmt.Printf("------------------------Leetcode Problem 118------------------------\n")
for _, q := range qs {
_, p := q.ans118, q.para118
fmt.Printf("【input】:%v 【output】:%v\n", p, generate(p.numRows))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0118.Pascals-Triangle/118. Pascals Triangle.go | leetcode/0118.Pascals-Triangle/118. Pascals Triangle.go | package leetcode
func generate(numRows int) [][]int {
result := [][]int{}
for i := 0; i < numRows; i++ {
row := []int{}
for j := 0; j < i+1; j++ {
if j == 0 || j == i {
row = append(row, 1)
} else if i > 1 {
row = append(row, result[i-1][j-1]+result[i-1][j])
}
}
result = append(result, row)
}
return result
}
| 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.