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/0914.X-of-a-Kind-in-a-Deck-of-Cards/914. X of a Kind in a Deck of Cards.go | leetcode/0914.X-of-a-Kind-in-a-Deck-of-Cards/914. X of a Kind in a Deck of Cards.go | package leetcode
func hasGroupsSizeX(deck []int) bool {
if len(deck) < 2 {
return false
}
m, g := map[int]int{}, -1
for _, d := range deck {
m[d]++
}
for _, v := range m {
if g == -1 {
g = v
} else {
g = gcd(g, v)
}
}
return g >= 2
}
func gcd(a, b int) int {
if a == 0 {
return b
}
return gcd(b%a, a)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0914.X-of-a-Kind-in-a-Deck-of-Cards/914. X of a Kind in a Deck of Cards_test.go | leetcode/0914.X-of-a-Kind-in-a-Deck-of-Cards/914. X of a Kind in a Deck of Cards_test.go | package leetcode
import (
"fmt"
"testing"
)
type question914 struct {
para914
ans914
}
// para 是参数
// one 代表第一个参数
type para914 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans914 struct {
one bool
}
func Test_Problem914(t *testing.T) {
qs := []question914{
{
para914{[]int{1, 2, 3, 4, 4, 3, 2, 1}},
ans914{true},
},
{
para914{[]int{1, 1, 1, 2, 2, 2, 3, 3}},
ans914{false},
},
{
para914{[]int{1}},
ans914{false},
},
{
para914{[]int{1, 1}},
ans914{true},
},
{
para914{[]int{1, 1, 2, 2, 2, 2}},
ans914{true},
},
}
fmt.Printf("------------------------Leetcode Problem 914------------------------\n")
for _, q := range qs {
_, p := q.ans914, q.para914
fmt.Printf("【input】:%v 【output】:%v\n", p, hasGroupsSizeX(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/0306.Additive-Number/306. Additive Number.go | leetcode/0306.Additive-Number/306. Additive Number.go | package leetcode
import (
"strconv"
"strings"
)
// This function controls various combinations as starting points
func isAdditiveNumber(num string) bool {
if len(num) < 3 {
return false
}
for firstEnd := 0; firstEnd < len(num)/2; firstEnd++ {
if num[0] == '0' && firstEnd > 0 {
break
}
first, _ := strconv.Atoi(num[:firstEnd+1])
for secondEnd := firstEnd + 1; max(firstEnd, secondEnd-firstEnd) <= len(num)-secondEnd; secondEnd++ {
if num[firstEnd+1] == '0' && secondEnd-firstEnd > 1 {
break
}
second, _ := strconv.Atoi(num[firstEnd+1 : secondEnd+1])
if recursiveCheck(num, first, second, secondEnd+1) {
return true
}
}
}
return false
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
// Propagate for rest of the string
func recursiveCheck(num string, x1 int, x2 int, left int) bool {
if left == len(num) {
return true
}
if strings.HasPrefix(num[left:], strconv.Itoa(x1+x2)) {
return recursiveCheck(num, x2, x1+x2, left+len(strconv.Itoa(x1+x2)))
}
return false
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0306.Additive-Number/306. Additive Number_test.go | leetcode/0306.Additive-Number/306. Additive Number_test.go | package leetcode
import (
"fmt"
"testing"
)
type question306 struct {
para306
ans306
}
// para 是参数
// one 代表第一个参数
type para306 struct {
one string
}
// ans 是答案
// one 代表第一个答案
type ans306 struct {
one bool
}
func Test_Problem306(t *testing.T) {
qs := []question306{
{
para306{"112358"},
ans306{true},
},
{
para306{"199100199"},
ans306{true},
},
}
fmt.Printf("------------------------Leetcode Problem 306------------------------\n")
for _, q := range qs {
_, p := q.ans306, q.para306
fmt.Printf("【input】:%v 【output】:%v\n", p, isAdditiveNumber(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/0812.Largest-Triangle-Area/812. Largest Triangle Area.go | leetcode/0812.Largest-Triangle-Area/812. Largest Triangle Area.go | package leetcode
func largestTriangleArea(points [][]int) float64 {
maxArea, n := 0.0, len(points)
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
for k := j + 1; k < n; k++ {
maxArea = max(maxArea, area(points[i], points[j], points[k]))
}
}
}
return maxArea
}
func area(p1, p2, p3 []int) float64 {
return abs(p1[0]*p2[1]+p2[0]*p3[1]+p3[0]*p1[1]-p1[0]*p3[1]-p2[0]*p1[1]-p3[0]*p2[1]) / 2
}
func abs(num int) float64 {
if num < 0 {
num = -num
}
return float64(num)
}
func max(a, b float64) float64 {
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/0812.Largest-Triangle-Area/812. Largest Triangle Area_test.go | leetcode/0812.Largest-Triangle-Area/812. Largest Triangle Area_test.go | package leetcode
import (
"fmt"
"testing"
)
type question812 struct {
para812
ans812
}
// para 是参数
// one 代表第一个参数
type para812 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans812 struct {
one float64
}
func Test_Problem812(t *testing.T) {
qs := []question812{
{
para812{[][]int{{0, 0}, {0, 1}, {1, 0}, {0, 2}, {2, 0}}},
ans812{2.0},
},
}
fmt.Printf("------------------------Leetcode Problem 812------------------------\n")
for _, q := range qs {
_, p := q.ans812, q.para812
fmt.Printf("【input】:%v 【output】:%v\n", p, largestTriangleArea(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/0347.Top-K-Frequent-Elements/347. Top K Frequent Elements.go | leetcode/0347.Top-K-Frequent-Elements/347. Top K Frequent Elements.go | package leetcode
import "container/heap"
func topKFrequent(nums []int, k int) []int {
m := make(map[int]int)
for _, n := range nums {
m[n]++
}
q := PriorityQueue{}
for key, count := range m {
heap.Push(&q, &Item{key: key, count: count})
}
var result []int
for len(result) < k {
item := heap.Pop(&q).(*Item)
result = append(result, item.key)
}
return result
}
// Item define
type Item struct {
key int
count int
}
// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item
func (pq PriorityQueue) Len() int {
return len(pq)
}
func (pq PriorityQueue) Less(i, j int) bool {
// 注意:因为golang中的heap是按最小堆组织的,所以count越大,Less()越小,越靠近堆顶.
return pq[i].count > pq[j].count
}
func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
// Push define
func (pq *PriorityQueue) Push(x interface{}) {
item := x.(*Item)
*pq = append(*pq, item)
}
// Pop define
func (pq *PriorityQueue) Pop() interface{} {
n := len(*pq)
item := (*pq)[n-1]
*pq = (*pq)[:n-1]
return item
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0347.Top-K-Frequent-Elements/347. Top K Frequent Elements_test.go | leetcode/0347.Top-K-Frequent-Elements/347. Top K Frequent Elements_test.go | package leetcode
import (
"fmt"
"testing"
)
type question347 struct {
para347
ans347
}
// para 是参数
// one 代表第一个参数
type para347 struct {
one []int
two int
}
// ans 是答案
// one 代表第一个答案
type ans347 struct {
one []int
}
func Test_Problem347(t *testing.T) {
qs := []question347{
{
para347{[]int{1, 1, 1, 2, 2, 3}, 2},
ans347{[]int{1, 2}},
},
{
para347{[]int{1}, 1},
ans347{[]int{1}},
},
}
fmt.Printf("------------------------Leetcode Problem 347------------------------\n")
for _, q := range qs {
_, p := q.ans347, q.para347
fmt.Printf("【input】:%v 【output】:%v\n", p, topKFrequent(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/0462.Minimum-Moves-to-Equal-Array-Elements-II/462. Minimum Moves to Equal Array Elements II_test.go | leetcode/0462.Minimum-Moves-to-Equal-Array-Elements-II/462. Minimum Moves to Equal Array Elements II_test.go | package leetcode
import (
"fmt"
"testing"
)
type question462 struct {
para462
ans462
}
// para 是参数
// one 代表第一个参数
type para462 struct {
nums []int
}
// ans 是答案
// one 代表第一个答案
type ans462 struct {
one int
}
func Test_Problem462(t *testing.T) {
qs := []question462{
{
para462{[]int{}},
ans462{0},
},
{
para462{[]int{1, 2, 3}},
ans462{2},
},
{
para462{[]int{1, 10, 2, 9}},
ans462{16},
},
{
para462{[]int{1, 0, 0, 8, 6}},
ans462{14},
},
}
fmt.Printf("------------------------Leetcode Problem 462------------------------\n")
for _, q := range qs {
_, p := q.ans462, q.para462
fmt.Printf("【input】:%v 【output】:%v\n", p, minMoves2(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/0462.Minimum-Moves-to-Equal-Array-Elements-II/462. Minimum Moves to Equal Array Elements II.go | leetcode/0462.Minimum-Moves-to-Equal-Array-Elements-II/462. Minimum Moves to Equal Array Elements II.go | package leetcode
import (
"math"
"sort"
)
func minMoves2(nums []int) int {
if len(nums) == 0 {
return 0
}
moves, mid := 0, len(nums)/2
sort.Ints(nums)
for i := range nums {
if i == mid {
continue
}
moves += int(math.Abs(float64(nums[mid] - nums[i])))
}
return moves
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1877.Minimize-Maximum-Pair-Sum-in-Array/1877. Minimize Maximum Pair Sum in Array.go | leetcode/1877.Minimize-Maximum-Pair-Sum-in-Array/1877. Minimize Maximum Pair Sum in Array.go | package leetcode
import "sort"
func minPairSum(nums []int) int {
sort.Ints(nums)
n, res := len(nums), 0
for i, val := range nums[:n/2] {
res = max(res, val+nums[n-1-i])
}
return res
}
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/1877.Minimize-Maximum-Pair-Sum-in-Array/1877. Minimize Maximum Pair Sum in Array_test.go | leetcode/1877.Minimize-Maximum-Pair-Sum-in-Array/1877. Minimize Maximum Pair Sum in Array_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1877 struct {
para1877
ans1877
}
// para 是参数
// one 代表第一个参数
type para1877 struct {
nums []int
}
// ans 是答案
// one 代表第一个答案
type ans1877 struct {
one int
}
func Test_Problem1877(t *testing.T) {
qs := []question1877{
{
para1877{[]int{2, 2, 1, 2, 1}},
ans1877{3},
},
{
para1877{[]int{100, 1, 1000}},
ans1877{1001},
},
{
para1877{[]int{1, 2, 3, 4, 5}},
ans1877{6},
},
{
para1877{[]int{3, 5, 2, 3}},
ans1877{7},
},
{
para1877{[]int{3, 5, 4, 2, 4, 6}},
ans1877{8},
},
}
fmt.Printf("------------------------Leetcode Problem 1877------------------------\n")
for _, q := range qs {
_, p := q.ans1877, q.para1877
fmt.Printf("【input】:%v 【output】:%v\n", p, minPairSum(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/0826.Most-Profit-Assigning-Work/826. Most Profit Assigning Work_test.go | leetcode/0826.Most-Profit-Assigning-Work/826. Most Profit Assigning Work_test.go | package leetcode
import (
"fmt"
"testing"
)
type question826 struct {
para826
ans826
}
// para 是参数
// one 代表第一个参数
type para826 struct {
one []int
two []int
three []int
}
// ans 是答案
// one 代表第一个答案
type ans826 struct {
one int
}
func Test_Problem826(t *testing.T) {
qs := []question826{
{
para826{[]int{2, 4, 6, 8, 10}, []int{10, 20, 30, 40, 50}, []int{4, 5, 6, 7}},
ans826{100},
},
{
para826{[]int{85, 47, 57}, []int{24, 66, 99}, []int{40, 25, 25}},
ans826{0},
},
}
fmt.Printf("------------------------Leetcode Problem 826------------------------\n")
for _, q := range qs {
_, p := q.ans826, q.para826
fmt.Printf("【input】:%v 【output】:%v\n", p, maxProfitAssignment(p.one, p.two, p.three))
}
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/0826.Most-Profit-Assigning-Work/826. Most Profit Assigning Work.go | leetcode/0826.Most-Profit-Assigning-Work/826. Most Profit Assigning Work.go | package leetcode
import (
"fmt"
"sort"
)
// Task define
type Task struct {
Difficulty int
Profit int
}
// Tasks define
type Tasks []Task
// Len define
func (p Tasks) Len() int { return len(p) }
// Swap define
func (p Tasks) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// SortByDiff define
type SortByDiff struct{ Tasks }
// Less define
func (p SortByDiff) Less(i, j int) bool {
return p.Tasks[i].Difficulty < p.Tasks[j].Difficulty
}
func maxProfitAssignment(difficulty []int, profit []int, worker []int) int {
if len(difficulty) == 0 || len(profit) == 0 || len(worker) == 0 {
return 0
}
tasks, res, index := []Task{}, 0, 0
for i := 0; i < len(difficulty); i++ {
tasks = append(tasks, Task{Difficulty: difficulty[i], Profit: profit[i]})
}
sort.Sort(SortByDiff{tasks})
sort.Ints(worker)
for i := 1; i < len(tasks); i++ {
tasks[i].Profit = max(tasks[i].Profit, tasks[i-1].Profit)
}
fmt.Printf("tasks = %v worker = %v\n", tasks, worker)
for _, w := range worker {
for index < len(difficulty) && w >= tasks[index].Difficulty {
index++
}
fmt.Printf("tasks【index】 = %v\n", tasks[index])
if index > 0 {
res += tasks[index-1].Profit
}
}
return res
}
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/0987.Vertical-Order-Traversal-of-a-Binary-Tree/987. Vertical Order Traversal of a Binary Tree.go | leetcode/0987.Vertical-Order-Traversal-of-a-Binary-Tree/987. Vertical Order Traversal of a Binary Tree.go | package leetcode
import (
"math"
"sort"
"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
* }
*/
type node struct {
x, y, val int
}
func verticalTraversal(root *TreeNode) [][]int {
var dfs func(root *TreeNode, x, y int)
var nodes []node
dfs = func(root *TreeNode, x, y int) {
if root == nil {
return
}
nodes = append(nodes, node{x, y, root.Val})
dfs(root.Left, x+1, y-1)
dfs(root.Right, x+1, y+1)
}
dfs(root, 0, 0)
sort.Slice(nodes, func(i, j int) bool {
a, b := nodes[i], nodes[j]
return a.y < b.y || a.y == b.y &&
(a.x < b.x || a.x == b.x && a.val < b.val)
})
var res [][]int
lastY := math.MinInt32
for _, node := range nodes {
if lastY != node.y {
res = append(res, []int{node.val})
lastY = node.y
} else {
res[len(res)-1] = append(res[len(res)-1], node.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/0987.Vertical-Order-Traversal-of-a-Binary-Tree/987. Vertical Order Traversal of a Binary Tree_test.go | leetcode/0987.Vertical-Order-Traversal-of-a-Binary-Tree/987. Vertical Order Traversal of a Binary Tree_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question987 struct {
para987
ans987
}
// para 是参数
// one 代表第一个参数
type para987 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans987 struct {
one [][]int
}
func Test_Problem987(t *testing.T) {
qs := []question987{
{
para987{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}},
ans987{[][]int{{9}, {3, 15}, {20}, {7}}},
},
{
para987{[]int{1, 2, 3, 4, 5, 6, 7}},
ans987{[][]int{{4}, {2}, {1, 5, 6}, {3}, {7}}},
},
{
para987{[]int{1, 2, 3, 4, 6, 5, 7}},
ans987{[][]int{{4}, {2}, {1, 5, 6}, {3}, {7}}},
},
}
fmt.Printf("------------------------Leetcode Problem 987------------------------\n")
for _, q := range qs {
_, p := q.ans987, q.para987
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", verticalTraversal(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/0561.Array-Partition/561. Array Partition_test.go | leetcode/0561.Array-Partition/561. Array Partition_test.go | package leetcode
import (
"fmt"
"testing"
)
type question561 struct {
para561
ans561
}
// para 是参数
// one 代表第一个参数
type para561 struct {
nums []int
}
// ans 是答案
// one 代表第一个答案
type ans561 struct {
one int
}
func Test_Problem561(t *testing.T) {
qs := []question561{
{
para561{[]int{}},
ans561{0},
},
{
para561{[]int{1, 4, 3, 2}},
ans561{4},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 561------------------------\n")
for _, q := range qs {
_, p := q.ans561, q.para561
fmt.Printf("【input】:%v 【output】:%v\n", p, arrayPairSum(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/0561.Array-Partition/561. Array Partition.go | leetcode/0561.Array-Partition/561. Array Partition.go | package leetcode
func arrayPairSum(nums []int) int {
array := [20001]int{}
for i := 0; i < len(nums); i++ {
array[nums[i]+10000]++
}
flag, sum := true, 0
for i := 0; i < len(array); i++ {
for array[i] > 0 {
if flag {
sum = sum + i - 10000
}
flag = !flag
array[i]--
}
}
return sum
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0103.Binary-Tree-Zigzag-Level-Order-Traversal/103. Binary Tree Zigzag Level Order Traversal_test.go | leetcode/0103.Binary-Tree-Zigzag-Level-Order-Traversal/103. Binary Tree Zigzag Level Order Traversal_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question103 struct {
para103
ans103
}
// para 是参数
// one 代表第一个参数
type para103 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans103 struct {
one [][]int
}
func Test_Problem103(t *testing.T) {
qs := []question103{
{
para103{[]int{}},
ans103{[][]int{}},
},
{
para103{[]int{1}},
ans103{[][]int{{1}}},
},
{
para103{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}},
ans103{[][]int{{3}, {9, 20}, {15, 7}}},
},
{
para103{[]int{1, 2, 3, 4, structures.NULL, structures.NULL, 5}},
ans103{[][]int{{1}, {3, 2}, {4, 5}}},
},
}
fmt.Printf("------------------------Leetcode Problem 103------------------------\n")
for _, q := range qs {
_, p := q.ans103, q.para103
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", zigzagLevelOrder(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/0103.Binary-Tree-Zigzag-Level-Order-Traversal/103. Binary Tree Zigzag Level Order Traversal.go | leetcode/0103.Binary-Tree-Zigzag-Level-Order-Traversal/103. Binary Tree Zigzag Level Order Traversal.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 解法一
func zigzagLevelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
queue := []*TreeNode{}
queue = append(queue, root)
curNum, nextLevelNum, res, tmp, curDir := 1, 0, [][]int{}, []int{}, 0
for len(queue) != 0 {
if curNum > 0 {
node := queue[0]
if node.Left != nil {
queue = append(queue, node.Left)
nextLevelNum++
}
if node.Right != nil {
queue = append(queue, node.Right)
nextLevelNum++
}
curNum--
tmp = append(tmp, node.Val)
queue = queue[1:]
}
if curNum == 0 {
if curDir == 1 {
for i, j := 0, len(tmp)-1; i < j; i, j = i+1, j-1 {
tmp[i], tmp[j] = tmp[j], tmp[i]
}
}
res = append(res, tmp)
curNum = nextLevelNum
nextLevelNum = 0
tmp = []int{}
if curDir == 0 {
curDir = 1
} else {
curDir = 0
}
}
}
return res
}
// 解法二 递归
func zigzagLevelOrder0(root *TreeNode) [][]int {
var res [][]int
search(root, 0, &res)
return res
}
func search(root *TreeNode, depth int, res *[][]int) {
if root == nil {
return
}
for len(*res) < depth+1 {
*res = append(*res, []int{})
}
if depth%2 == 0 {
(*res)[depth] = append((*res)[depth], root.Val)
} else {
(*res)[depth] = append([]int{root.Val}, (*res)[depth]...)
}
search(root.Left, depth+1, res)
search(root.Right, depth+1, res)
}
// 解法三 BFS
func zigzagLevelOrder1(root *TreeNode) [][]int {
res := [][]int{}
if root == nil {
return res
}
q := []*TreeNode{root}
size, i, j, lay, tmp, flag := 0, 0, 0, []int{}, []*TreeNode{}, false
for len(q) > 0 {
size = len(q)
tmp = []*TreeNode{}
lay = make([]int, size)
j = size - 1
for i = 0; i < size; i++ {
root = q[0]
q = q[1:]
if !flag {
lay[i] = root.Val
} else {
lay[j] = root.Val
j--
}
if root.Left != nil {
tmp = append(tmp, root.Left)
}
if root.Right != nil {
tmp = append(tmp, root.Right)
}
}
res = append(res, lay)
flag = !flag
q = tmp
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0061.Rotate-List/61. Rotate List_test.go | leetcode/0061.Rotate-List/61. Rotate List_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question61 struct {
para61
ans61
}
// para 是参数
// one 代表第一个参数
type para61 struct {
one []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans61 struct {
one []int
}
func Test_Problem61(t *testing.T) {
qs := []question61{
{
para61{[]int{1, 2, 3, 4, 5}, 2},
ans61{[]int{4, 5, 1, 2, 3}},
},
{
para61{[]int{1, 2, 3, 4, 5}, 3},
ans61{[]int{4, 5, 1, 2, 3}},
},
{
para61{[]int{0, 1, 2}, 4},
ans61{[]int{2, 0, 1}},
},
{
para61{[]int{1, 1, 1, 2}, 3},
ans61{[]int{1, 1, 2, 1}},
},
{
para61{[]int{1}, 10},
ans61{[]int{1}},
},
{
para61{[]int{}, 100},
ans61{[]int{}},
},
}
fmt.Printf("------------------------Leetcode Problem 61------------------------\n")
for _, q := range qs {
_, p := q.ans61, q.para61
fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(rotateRight(structures.Ints2List(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/0061.Rotate-List/61. Rotate List.go | leetcode/0061.Rotate-List/61. Rotate 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 rotateRight(head *ListNode, k int) *ListNode {
if head == nil || head.Next == nil || k == 0 {
return head
}
newHead := &ListNode{Val: 0, Next: head}
len := 0
cur := newHead
for cur.Next != nil {
len++
cur = cur.Next
}
if (k % len) == 0 {
return head
}
cur.Next = head
cur = newHead
for i := len - k%len; i > 0; i-- {
cur = cur.Next
}
res := &ListNode{Val: 0, Next: cur.Next}
cur.Next = nil
return res.Next
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0065.Valid-Number/65. Valid Number.go | leetcode/0065.Valid-Number/65. Valid Number.go | package leetcode
func isNumber(s string) bool {
numFlag, dotFlag, eFlag := false, false, false
for i := 0; i < len(s); i++ {
if '0' <= s[i] && s[i] <= '9' {
numFlag = true
} else if s[i] == '.' && !dotFlag && !eFlag {
dotFlag = true
} else if (s[i] == 'e' || s[i] == 'E') && !eFlag && numFlag {
eFlag = true
numFlag = false // reJudge integer after 'e' or 'E'
} else if (s[i] == '+' || s[i] == '-') && (i == 0 || s[i-1] == 'e' || s[i-1] == 'E') {
continue
} else {
return false
}
}
// avoid case: s == '.' or 'e/E' or '+/-' and etc...
// string s must have num
return numFlag
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0065.Valid-Number/65. Valid Number_test.go | leetcode/0065.Valid-Number/65. Valid Number_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem65(t *testing.T) {
tcs := []struct {
s string
ans bool
}{
{
"0",
true,
},
{
"e",
false,
},
{
".",
false,
},
{
".1",
true,
},
}
fmt.Printf("------------------------Leetcode Problem 65------------------------\n")
for _, tc := range tcs {
fmt.Printf("【input】:%v 【output】:%v\n", tc, isNumber(tc.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/0918.Maximum-Sum-Circular-Subarray/918. Maximum Sum Circular Subarray.go | leetcode/0918.Maximum-Sum-Circular-Subarray/918. Maximum Sum Circular Subarray.go | package leetcode
import "math"
func maxSubarraySumCircular(nums []int) int {
var max1, max2, sum int
// case: no circulation
max1 = int(math.Inf(-1))
l := len(nums)
for i := 0; i < l; i++ {
sum += nums[i]
if sum > max1 {
max1 = sum
}
if sum < 1 {
sum = 0
}
}
// case: circling
arr_sum := 0
for i := 0; i < l; i++ {
arr_sum += nums[i]
}
sum = 0
min_sum := 0
for i := 1; i < l-1; i++ {
sum += nums[i]
if sum >= 0 {
sum = 0
}
if sum < min_sum {
min_sum = sum
}
}
max2 = arr_sum - min_sum
return max(max1, max2)
}
func max(nums ...int) int {
max := int(math.Inf(-1))
for _, num := range nums {
if num > max {
max = num
}
}
return max
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0918.Maximum-Sum-Circular-Subarray/918. Maximum Sum Circular Subarray_test.go | leetcode/0918.Maximum-Sum-Circular-Subarray/918. Maximum Sum Circular Subarray_test.go | package leetcode
import (
"fmt"
"testing"
)
type question918 struct {
para918
ans918
}
// para 是参数
// one 代表第一个参数
type para918 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans918 struct {
one int
}
func Test_Problem918(t *testing.T) {
qs := []question918{
{
para918{[]int{1, -2, 3, -2}},
ans918{3},
},
{
para918{[]int{5, -3, 5}},
ans918{10},
},
{
para918{[]int{3, -1, 2, -1}},
ans918{4},
},
{
para918{[]int{3, -2, 2, -3}},
ans918{3},
},
{
para918{[]int{-2, -3, -1}},
ans918{-1},
},
}
fmt.Printf("------------------------Leetcode Problem 918------------------------\n")
for _, q := range qs {
_, p := q.ans918, q.para918
fmt.Printf("【input】:%v 【output】:%v\n", p, maxSubarraySumCircular(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/0419.Battleships-in-a-Board/419. Battleships in a Board.go | leetcode/0419.Battleships-in-a-Board/419. Battleships in a Board.go | package leetcode
func countBattleships(board [][]byte) (ans int) {
if len(board) == 0 || len(board[0]) == 0 {
return 0
}
for i := range board {
for j := range board[i] {
if board[i][j] == 'X' {
if i > 0 && board[i-1][j] == 'X' {
continue
}
if j > 0 && board[i][j-1] == 'X' {
continue
}
ans++
}
}
}
return
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0419.Battleships-in-a-Board/419. Battleships in a Board_test.go | leetcode/0419.Battleships-in-a-Board/419. Battleships in a Board_test.go | package leetcode
import (
"fmt"
"testing"
"unsafe"
)
type question419 struct {
para419
ans419
}
// para 是参数
// one 代表第一个参数
type para419 struct {
one [][]byte
}
// ans 是答案
// one 代表第一个答案
type ans419 struct {
one int
}
func Test_Problem419(t *testing.T) {
qs := []question419{
{
para419{[][]byte{{'X', '.', '.', 'X'}, {'.', '.', '.', 'X'}, {'.', '.', '.', 'X'}}},
ans419{2},
},
{
para419{[][]byte{{'.'}}},
ans419{0},
},
}
fmt.Printf("------------------------Leetcode Problem 419------------------------\n")
for _, q := range qs {
_, p := q.ans419, q.para419
fmt.Printf("【input】:%v 【output】:%v\n", bytesArrayToStringArray(p.one), countBattleships(p.one))
}
fmt.Printf("\n\n\n")
}
// 在运行go test时 为了更直观地显示[][]byte中的字符而非ASCII码数值
// bytesArrayToStringArray converts [][]byte to []string
func bytesArrayToStringArray(b [][]byte) []string {
s := make([]string, len(b))
for i := range b {
s[i] = fmt.Sprintf("[%v]", *(*string)(unsafe.Pointer(&b[i])))
}
return s
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0959.Regions-Cut-By-Slashes/959. Regions Cut By Slashes_test.go | leetcode/0959.Regions-Cut-By-Slashes/959. Regions Cut By Slashes_test.go | package leetcode
import (
"fmt"
"testing"
)
type question959 struct {
para959
ans959
}
// para 是参数
// one 代表第一个参数
type para959 struct {
one []string
}
// ans 是答案
// one 代表第一个答案
type ans959 struct {
one int
}
func Test_Problem959(t *testing.T) {
qs := []question959{
{
para959{[]string{" /", "/ "}},
ans959{2},
},
{
para959{[]string{" /", " "}},
ans959{1},
},
{
para959{[]string{"\\/", "/\\"}},
ans959{4},
},
{
para959{[]string{"/\\", "\\/"}},
ans959{5},
},
{
para959{[]string{"//", "/ "}},
ans959{3},
},
}
fmt.Printf("------------------------Leetcode Problem 959------------------------\n")
for _, q := range qs {
_, p := q.ans959, q.para959
fmt.Printf("【input】:%v 【output】:%v\n", p, regionsBySlashes(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/0959.Regions-Cut-By-Slashes/959. Regions Cut By Slashes.go | leetcode/0959.Regions-Cut-By-Slashes/959. Regions Cut By Slashes.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/template"
)
func regionsBySlashes(grid []string) int {
size := len(grid)
uf := template.UnionFind{}
uf.Init(4 * size * size)
for i := 0; i < size; i++ {
for j := 0; j < size; j++ {
switch grid[i][j] {
case '\\':
uf.Union(getFaceIdx(size, i, j, 0), getFaceIdx(size, i, j, 1))
uf.Union(getFaceIdx(size, i, j, 2), getFaceIdx(size, i, j, 3))
case '/':
uf.Union(getFaceIdx(size, i, j, 0), getFaceIdx(size, i, j, 3))
uf.Union(getFaceIdx(size, i, j, 2), getFaceIdx(size, i, j, 1))
case ' ':
uf.Union(getFaceIdx(size, i, j, 0), getFaceIdx(size, i, j, 1))
uf.Union(getFaceIdx(size, i, j, 2), getFaceIdx(size, i, j, 1))
uf.Union(getFaceIdx(size, i, j, 2), getFaceIdx(size, i, j, 3))
}
if i < size-1 {
uf.Union(getFaceIdx(size, i, j, 2), getFaceIdx(size, i+1, j, 0))
}
if j < size-1 {
uf.Union(getFaceIdx(size, i, j, 1), getFaceIdx(size, i, j+1, 3))
}
}
}
count := 0
for i := 0; i < 4*size*size; i++ {
if uf.Find(i) == i {
count++
}
}
return count
}
func getFaceIdx(size, i, j, k int) int {
return 4*(i*size+j) + k
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0838.Push-Dominoes/838. Push Dominoes_test.go | leetcode/0838.Push-Dominoes/838. Push Dominoes_test.go | package leetcode
import (
"fmt"
"testing"
)
type question838 struct {
para838
ans838
}
// para 是参数
// one 代表第一个参数
type para838 struct {
one string
}
// ans 是答案
// one 代表第一个答案
type ans838 struct {
one string
}
func Test_Problem838(t *testing.T) {
qs := []question838{
{
para838{".L.R...LR..L.."},
ans838{"LL.RR.LLRRLL.."},
},
{
para838{"RR.L"},
ans838{"RR.L"},
},
{
para838{".L.R."},
ans838{"LL.RR"},
},
}
fmt.Printf("------------------------Leetcode Problem 838------------------------\n")
for _, q := range qs {
_, p := q.ans838, q.para838
fmt.Printf("【input】:%v 【output】:%v\n", p, pushDominoes(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/0838.Push-Dominoes/838. Push Dominoes.go | leetcode/0838.Push-Dominoes/838. Push Dominoes.go | package leetcode
// 解法一
func pushDominoes(dominoes string) string {
d := []byte(dominoes)
for i := 0; i < len(d); {
j := i + 1
for j < len(d)-1 && d[j] == '.' {
j++
}
push(d[i : j+1])
i = j
}
return string(d)
}
func push(d []byte) {
first, last := 0, len(d)-1
switch d[first] {
case '.', 'L':
if d[last] == 'L' {
for ; first < last; first++ {
d[first] = 'L'
}
}
case 'R':
if d[last] == '.' || d[last] == 'R' {
for ; first <= last; first++ {
d[first] = 'R'
}
} else if d[last] == 'L' {
for first < last {
d[first] = 'R'
d[last] = 'L'
first++
last--
}
}
}
}
// 解法二
func pushDominoes1(dominoes string) string {
dominoes = "L" + dominoes + "R"
res := ""
for i, j := 0, 1; j < len(dominoes); j++ {
if dominoes[j] == '.' {
continue
}
if i > 0 {
res += string(dominoes[i])
}
middle := j - i - 1
if dominoes[i] == dominoes[j] {
for k := 0; k < middle; k++ {
res += string(dominoes[i])
}
} else if dominoes[i] == 'L' && dominoes[j] == 'R' {
for k := 0; k < middle; k++ {
res += string('.')
}
} else {
for k := 0; k < middle/2; k++ {
res += string('R')
}
for k := 0; k < middle%2; k++ {
res += string('.')
}
for k := 0; k < middle/2; k++ {
res += string('L')
}
}
i = j
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0887.Super-Egg-Drop/887. Super Egg Drop_test.go | leetcode/0887.Super-Egg-Drop/887. Super Egg Drop_test.go | package leetcode
import (
"fmt"
"testing"
)
type question887 struct {
para887
ans887
}
// para 是参数
// one 代表第一个参数
type para887 struct {
k int
n int
}
// ans 是答案
// one 代表第一个答案
type ans887 struct {
one int
}
func Test_Problem887(t *testing.T) {
qs := []question887{
{
para887{1, 2},
ans887{2},
},
{
para887{2, 6},
ans887{3},
},
{
para887{3, 14},
ans887{4},
},
}
fmt.Printf("------------------------Leetcode Problem 887------------------------\n")
for _, q := range qs {
_, p := q.ans887, q.para887
fmt.Printf("【input】:%v 【output】:%v\n", p, superEggDrop(p.k, 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/0887.Super-Egg-Drop/887. Super Egg Drop.go | leetcode/0887.Super-Egg-Drop/887. Super Egg Drop.go | package leetcode
// 解法一 二分搜索
func superEggDrop(K int, N int) int {
low, high := 1, N
for low < high {
mid := low + (high-low)>>1
if counterF(K, N, mid) >= N {
high = mid
} else {
low = mid + 1
}
}
return low
}
// 计算二项式和,特殊的第一项 C(t,0) = 1
func counterF(k, n, mid int) int {
res, sum := 1, 0
for i := 1; i <= k && sum < n; i++ {
res *= mid - i + 1
res /= i
sum += res
}
return sum
}
// 解法二 动态规划 DP
func superEggDrop1(K int, N int) int {
dp, step := make([]int, K+1), 0
for ; dp[K] < N; step++ {
for i := K; i > 0; i-- {
dp[i] = (1 + dp[i] + dp[i-1])
}
}
return step
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0636.Exclusive-Time-of-Functions/636. Exclusive Time of Functions_test.go | leetcode/0636.Exclusive-Time-of-Functions/636. Exclusive Time of Functions_test.go | package leetcode
import (
"fmt"
"testing"
)
type question636 struct {
para636
ans636
}
// para 是参数
// one 代表第一个参数
type para636 struct {
n int
one []string
}
// ans 是答案
// one 代表第一个答案
type ans636 struct {
one []int
}
func Test_Problem636(t *testing.T) {
qs := []question636{
{
para636{2, []string{"0:start:0", "0:start:2", "0:end:5", "1:start:7", "1:end:7", "0:end:8"}},
ans636{[]int{8, 1}},
},
{
para636{2, []string{"0:start:0", "0:start:2", "0:end:5", "1:start:6", "1:end:6", "0:end:7"}},
ans636{[]int{7, 1}},
},
{
para636{2, []string{"0:start:0", "1:start:2", "1:end:5", "0:end:6"}},
ans636{[]int{3, 4}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 636------------------------\n")
for _, q := range qs {
_, p := q.ans636, q.para636
fmt.Printf("【input】:%v 【output】:%v\n", p, exclusiveTime(p.n, p.one))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0636.Exclusive-Time-of-Functions/636. Exclusive Time of Functions.go | leetcode/0636.Exclusive-Time-of-Functions/636. Exclusive Time of Functions.go | package leetcode
import (
"strconv"
"strings"
)
type log struct {
id int
order string
time int
}
func exclusiveTime(n int, logs []string) []int {
res, lastLog, stack := make([]int, n), log{id: -1, order: "", time: 0}, []log{}
for i := 0; i < len(logs); i++ {
a := strings.Split(logs[i], ":")
id, _ := strconv.Atoi(a[0])
time, _ := strconv.Atoi(a[2])
if (lastLog.order == "start" && a[1] == "start") || (lastLog.order == "start" && a[1] == "end") {
res[lastLog.id] += time - lastLog.time
if a[1] == "end" {
res[lastLog.id]++
}
}
if lastLog.order == "end" && a[1] == "end" {
res[id] += time - lastLog.time
}
if lastLog.order == "end" && a[1] == "start" && len(stack) != 0 {
res[stack[len(stack)-1].id] += time - lastLog.time - 1
}
if a[1] == "start" {
stack = append(stack, log{id: id, order: a[1], time: time})
} else {
stack = stack[:len(stack)-1]
}
lastLog = log{id: id, order: a[1], time: time}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0413.Arithmetic-Slices/413. Arithmetic Slices.go | leetcode/0413.Arithmetic-Slices/413. Arithmetic Slices.go | package leetcode
func numberOfArithmeticSlices(A []int) int {
if len(A) < 3 {
return 0
}
res, dp := 0, 0
for i := 1; i < len(A)-1; i++ {
if A[i+1]-A[i] == A[i]-A[i-1] {
dp++
res += dp
} else {
dp = 0
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0413.Arithmetic-Slices/413. Arithmetic Slices_test.go | leetcode/0413.Arithmetic-Slices/413. Arithmetic Slices_test.go | package leetcode
import (
"fmt"
"testing"
)
type question413 struct {
para413
ans413
}
// para 是参数
// one 代表第一个参数
type para413 struct {
A []int
}
// ans 是答案
// one 代表第一个答案
type ans413 struct {
one int
}
func Test_Problem413(t *testing.T) {
qs := []question413{
{
para413{[]int{1, 2, 3, 4}},
ans413{3},
},
{
para413{[]int{1, 2, 3, 4, 9}},
ans413{3},
},
{
para413{[]int{1, 2, 3, 4, 5, 6, 7}},
ans413{3},
},
}
fmt.Printf("------------------------Leetcode Problem 413------------------------\n")
for _, q := range qs {
_, p := q.ans413, q.para413
fmt.Printf("【input】:%v 【output】:%v\n", p, numberOfArithmeticSlices(p.A))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0445.Add-Two-Numbers-II/445. Add Two Numbers II_test.go | leetcode/0445.Add-Two-Numbers-II/445. Add Two Numbers II_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question445 struct {
para445
ans445
}
// para 是参数
// one 代表第一个参数
type para445 struct {
one []int
another []int
}
// ans 是答案
// one 代表第一个答案
type ans445 struct {
one []int
}
func Test_Problem445(t *testing.T) {
qs := []question445{
{
para445{[]int{}, []int{}},
ans445{[]int{}},
},
{
para445{[]int{1}, []int{1}},
ans445{[]int{2}},
},
{
para445{[]int{1, 2, 3, 4}, []int{1, 2, 3, 4}},
ans445{[]int{2, 4, 6, 8}},
},
{
para445{[]int{1, 2, 3, 4, 5}, []int{1, 2, 3, 4, 5}},
ans445{[]int{2, 4, 6, 9, 0}},
},
{
para445{[]int{1}, []int{9, 9, 9, 9, 9}},
ans445{[]int{1, 0, 0, 0, 0, 0}},
},
{
para445{[]int{9, 9, 9, 9, 9}, []int{1}},
ans445{[]int{1, 0, 0, 0, 0, 0}},
},
{
para445{[]int{2, 4, 3}, []int{5, 6, 4}},
ans445{[]int{8, 0, 7}},
},
{
para445{[]int{1, 8, 3}, []int{7, 1}},
ans445{[]int{2, 5, 4}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 445------------------------\n")
for _, q := range qs {
_, p := q.ans445, q.para445
fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(addTwoNumbers445(structures.Ints2List(p.one), structures.Ints2List(p.another))))
}
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/0445.Add-Two-Numbers-II/445. Add Two Numbers II.go | leetcode/0445.Add-Two-Numbers-II/445. Add Two Numbers II.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// ListNode define
type ListNode = structures.ListNode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers445(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
l1Length := getLength(l1)
l2Length := getLength(l2)
newHeader := &ListNode{Val: 1, Next: nil}
if l1Length < l2Length {
newHeader.Next = addNode(l2, l1, l2Length-l1Length)
} else {
newHeader.Next = addNode(l1, l2, l1Length-l2Length)
}
if newHeader.Next.Val > 9 {
newHeader.Next.Val = newHeader.Next.Val % 10
return newHeader
}
return newHeader.Next
}
func addNode(l1 *ListNode, l2 *ListNode, offset int) *ListNode {
if l1 == nil {
return nil
}
var (
res, node *ListNode
)
if offset == 0 {
res = &ListNode{Val: l1.Val + l2.Val, Next: nil}
node = addNode(l1.Next, l2.Next, 0)
} else {
res = &ListNode{Val: l1.Val, Next: nil}
node = addNode(l1.Next, l2, offset-1)
}
if node != nil && node.Val > 9 {
res.Val++
node.Val = node.Val % 10
}
res.Next = node
return res
}
func getLength(l *ListNode) int {
count := 0
cur := l
for cur != nil {
count++
cur = cur.Next
}
return count
}
func addTwoNumbers1(l1 *ListNode, l2 *ListNode) *ListNode {
reservedL1 := reverseList(l1)
reservedL2 := reverseList(l2)
dummyHead := &ListNode{}
head := dummyHead
carry := 0
for reservedL1 != nil || reservedL2 != nil || carry > 0 {
val := carry
if reservedL1 != nil {
val = reservedL1.Val + val
reservedL1 = reservedL1.Next
}
if reservedL2 != nil {
val = reservedL2.Val + val
reservedL2 = reservedL2.Next
}
carry = val / 10
head.Next = &ListNode{Val: val % 10}
head = head.Next
}
return reverseList(dummyHead.Next)
}
func reverseList(head *ListNode) *ListNode {
var prev *ListNode
for head != nil {
tmp := head.Next
head.Next = prev
prev = head
head = tmp
}
return prev
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
stack1 := pushStack(l1)
stack2 := pushStack(l2)
dummyHead := &ListNode{}
head := dummyHead
carry := 0
for len(stack1) > 0 || len(stack2) > 0 || carry > 0 {
val := carry
if len(stack1) > 0 {
val = val + stack1[len(stack1)-1]
stack1 = stack1[:len(stack1)-1]
}
if len(stack2) > 0 {
val = val + stack2[len(stack2)-1]
stack2 = stack2[:len(stack2)-1]
}
carry = val / 10
tmp := head.Next
head.Next = &ListNode{Val: val % 10, Next: tmp}
}
return dummyHead.Next
}
func pushStack(l *ListNode) []int {
var stack []int
for l != nil {
stack = append(stack, l.Val)
l = l.Next
}
return stack
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0966.Vowel-Spellchecker/966. Vowel Spellchecker.go | leetcode/0966.Vowel-Spellchecker/966. Vowel Spellchecker.go | package leetcode
import "strings"
func spellchecker(wordlist []string, queries []string) []string {
wordsPerfect, wordsCap, wordsVowel := map[string]bool{}, map[string]string{}, map[string]string{}
for _, word := range wordlist {
wordsPerfect[word] = true
wordLow := strings.ToLower(word)
if _, ok := wordsCap[wordLow]; !ok {
wordsCap[wordLow] = word
}
wordLowVowel := devowel(wordLow)
if _, ok := wordsVowel[wordLowVowel]; !ok {
wordsVowel[wordLowVowel] = word
}
}
res, index := make([]string, len(queries)), 0
for _, query := range queries {
if _, ok := wordsPerfect[query]; ok {
res[index] = query
index++
continue
}
queryL := strings.ToLower(query)
if v, ok := wordsCap[queryL]; ok {
res[index] = v
index++
continue
}
queryLV := devowel(queryL)
if v, ok := wordsVowel[queryLV]; ok {
res[index] = v
index++
continue
}
res[index] = ""
index++
}
return res
}
func devowel(word string) string {
runes := []rune(word)
for k, c := range runes {
if c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' {
runes[k] = '*'
}
}
return string(runes)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0966.Vowel-Spellchecker/966. Vowel Spellchecker_test.go | leetcode/0966.Vowel-Spellchecker/966. Vowel Spellchecker_test.go | package leetcode
import (
"fmt"
"testing"
)
type question966 struct {
para966
ans966
}
// para 是参数
// one 代表第一个参数
type para966 struct {
wordlist []string
queries []string
}
// ans 是答案
// one 代表第一个答案
type ans966 struct {
one []string
}
func Test_Problem966(t *testing.T) {
qs := []question966{
{
para966{[]string{"KiTe", "kite", "hare", "Hare"}, []string{"kite", "Kite", "KiTe", "Hare", "HARE", "Hear", "hear", "keti", "keet", "keto"}},
ans966{[]string{"kite", "KiTe", "KiTe", "Hare", "hare", "", "", "KiTe", "", "KiTe"}},
},
}
fmt.Printf("------------------------Leetcode Problem 966------------------------\n")
for _, q := range qs {
_, p := q.ans966, q.para966
fmt.Printf("【input】:%v 【output】:%#v\n", p, spellchecker(p.wordlist, p.queries))
}
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/1518.Water-Bottles/1518.Water Bottles.go | leetcode/1518.Water-Bottles/1518.Water Bottles.go | package leetcode
func numWaterBottles(numBottles int, numExchange int) int {
if numBottles < numExchange {
return numBottles
}
quotient := numBottles / numExchange
reminder := numBottles % numExchange
ans := numBottles + quotient
for quotient+reminder >= numExchange {
quotient, reminder = (quotient+reminder)/numExchange, (quotient+reminder)%numExchange
ans += quotient
}
return ans
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1518.Water-Bottles/1518.Water Bottles_test.go | leetcode/1518.Water-Bottles/1518.Water Bottles_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1518 struct {
para1518
ans1518
}
// para 是参数
type para1518 struct {
numBottles int
numExchange int
}
// ans 是答案
type ans1518 struct {
ans int
}
func Test_Problem1518(t *testing.T) {
qs := []question1518{
{
para1518{9, 3},
ans1518{13},
},
{
para1518{15, 4},
ans1518{19},
},
{
para1518{5, 5},
ans1518{6},
},
{
para1518{2, 3},
ans1518{2},
},
}
fmt.Printf("------------------------Leetcode Problem 1518------------------------\n")
for _, q := range qs {
_, p := q.ans1518, q.para1518
fmt.Printf("【input】:%v 【output】:%v\n", p, numWaterBottles(p.numBottles, p.numExchange))
}
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/0102.Binary-Tree-Level-Order-Traversal/102. Binary Tree Level Order Traversal.go | leetcode/0102.Binary-Tree-Level-Order-Traversal/102. Binary Tree Level Order Traversal.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 解法一 BFS
func levelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
queue := []*TreeNode{root}
res := make([][]int, 0)
for len(queue) > 0 {
l := len(queue)
tmp := make([]int, 0, l)
for i := 0; i < l; i++ {
if queue[i].Left != nil {
queue = append(queue, queue[i].Left)
}
if queue[i].Right != nil {
queue = append(queue, queue[i].Right)
}
tmp = append(tmp, queue[i].Val)
}
queue = queue[l:]
res = append(res, tmp)
}
return res
}
// 解法二 DFS
func levelOrder1(root *TreeNode) [][]int {
var res [][]int
var dfsLevel func(node *TreeNode, level int)
dfsLevel = func(node *TreeNode, level int) {
if node == nil {
return
}
if len(res) == level {
res = append(res, []int{node.Val})
} else {
res[level] = append(res[level], node.Val)
}
dfsLevel(node.Left, level+1)
dfsLevel(node.Right, level+1)
}
dfsLevel(root, 0)
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0102.Binary-Tree-Level-Order-Traversal/102. Binary Tree Level Order Traversal_test.go | leetcode/0102.Binary-Tree-Level-Order-Traversal/102. Binary Tree Level Order Traversal_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question102 struct {
para102
ans102
}
// para 是参数
// one 代表第一个参数
type para102 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans102 struct {
one [][]int
}
func Test_Problem102(t *testing.T) {
qs := []question102{
{
para102{[]int{}},
ans102{[][]int{}},
},
{
para102{[]int{1}},
ans102{[][]int{{1}}},
},
{
para102{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}},
ans102{[][]int{{3}, {9, 20}, {15, 7}}},
},
}
fmt.Printf("------------------------Leetcode Problem 102------------------------\n")
for _, q := range qs {
_, p := q.ans102, q.para102
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", levelOrder(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/1642.Furthest-Building-You-Can-Reach/1642. Furthest Building You Can Reach_test.go | leetcode/1642.Furthest-Building-You-Can-Reach/1642. Furthest Building You Can Reach_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1642 struct {
para1642
ans1642
}
// para 是参数
// one 代表第一个参数
type para1642 struct {
heights []int
bricks int
ladders int
}
// ans 是答案
// one 代表第一个答案
type ans1642 struct {
one int
}
func Test_Problem1642(t *testing.T) {
qs := []question1642{
{
para1642{[]int{1, 5, 1, 2, 3, 4, 10000}, 4, 1},
ans1642{5},
},
{
para1642{[]int{4, 2, 7, 6, 9, 14, 12}, 5, 1},
ans1642{4},
},
{
para1642{[]int{4, 12, 2, 7, 3, 18, 20, 3, 19}, 10, 2},
ans1642{7},
},
{
para1642{[]int{14, 3, 19, 3}, 17, 0},
ans1642{3},
},
}
fmt.Printf("------------------------Leetcode Problem 1642------------------------\n")
for _, q := range qs {
_, p := q.ans1642, q.para1642
fmt.Printf("【input】:%v 【output】:%v \n", p, furthestBuilding(p.heights, p.bricks, p.ladders))
}
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/1642.Furthest-Building-You-Can-Reach/1642. Furthest Building You Can Reach.go | leetcode/1642.Furthest-Building-You-Can-Reach/1642. Furthest Building You Can Reach.go | package leetcode
import (
"container/heap"
)
func furthestBuilding(heights []int, bricks int, ladder int) int {
usedLadder := &heightDiffPQ{}
for i := 1; i < len(heights); i++ {
needbricks := heights[i] - heights[i-1]
if needbricks < 0 {
continue
}
if ladder > 0 {
heap.Push(usedLadder, needbricks)
ladder--
} else {
if len(*usedLadder) > 0 && needbricks > (*usedLadder)[0] {
needbricks, (*usedLadder)[0] = (*usedLadder)[0], needbricks
heap.Fix(usedLadder, 0)
}
if bricks -= needbricks; bricks < 0 {
return i - 1
}
}
}
return len(heights) - 1
}
type heightDiffPQ []int
func (pq heightDiffPQ) Len() int { return len(pq) }
func (pq heightDiffPQ) Less(i, j int) bool { return pq[i] < pq[j] }
func (pq heightDiffPQ) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] }
func (pq *heightDiffPQ) Push(x interface{}) { *pq = append(*pq, x.(int)) }
func (pq *heightDiffPQ) Pop() interface{} {
x := (*pq)[len(*pq)-1]
*pq = (*pq)[:len(*pq)-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/0668.Kth-Smallest-Number-in-Multiplication-Table/668. Kth Smallest Number in Multiplication Table.go | leetcode/0668.Kth-Smallest-Number-in-Multiplication-Table/668. Kth Smallest Number in Multiplication Table.go | package leetcode
import "math"
func findKthNumber(m int, n int, k int) int {
low, high := 1, m*n
for low < high {
mid := low + (high-low)>>1
if counterKthNum(m, n, mid) >= k {
high = mid
} else {
low = mid + 1
}
}
return low
}
func counterKthNum(m, n, mid int) int {
count := 0
for i := 1; i <= m; i++ {
count += int(math.Min(math.Floor(float64(mid)/float64(i)), float64(n)))
}
return count
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0668.Kth-Smallest-Number-in-Multiplication-Table/668. Kth Smallest Number in Multiplication Table_test.go | leetcode/0668.Kth-Smallest-Number-in-Multiplication-Table/668. Kth Smallest Number in Multiplication Table_test.go | package leetcode
import (
"fmt"
"testing"
)
type question668 struct {
para668
ans668
}
// para 是参数
// one 代表第一个参数
type para668 struct {
m int
n int
k int
}
// ans 是答案
// one 代表第一个答案
type ans668 struct {
one int
}
func Test_Problem668(t *testing.T) {
qs := []question668{
{
para668{3, 3, 5},
ans668{3},
},
{
para668{2, 3, 6},
ans668{6},
},
{
para668{1, 3, 2},
ans668{2},
},
{
para668{42, 34, 401},
ans668{126},
},
{
para668{7341, 13535, 12330027},
ans668{2673783},
},
}
fmt.Printf("------------------------Leetcode Problem 668------------------------\n")
for _, q := range qs {
_, p := q.ans668, q.para668
fmt.Printf("【input】:%v 【output】:%v\n", p, findKthNumber(p.m, p.n, p.k))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0027.Remove-Element/27. Remove Element.go | leetcode/0027.Remove-Element/27. Remove Element.go | package leetcode
func removeElement(nums []int, val int) int {
if len(nums) == 0 {
return 0
}
j := 0
for i := 0; i < len(nums); i++ {
if nums[i] != val {
if i != j {
nums[i], nums[j] = nums[j], nums[i]
}
j++
}
}
return j
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0027.Remove-Element/27. Remove Element_test.go | leetcode/0027.Remove-Element/27. Remove Element_test.go | package leetcode
import (
"fmt"
"testing"
)
type question27 struct {
para27
ans27
}
// para 是参数
// one 代表第一个参数
type para27 struct {
one []int
two int
}
// ans 是答案
// one 代表第一个答案
type ans27 struct {
one int
}
func Test_Problem27(t *testing.T) {
qs := []question27{
{
para27{[]int{1, 0, 1}, 1},
ans27{1},
},
{
para27{[]int{0, 1, 0, 3, 0, 12}, 0},
ans27{3},
},
{
para27{[]int{0, 1, 0, 3, 0, 0, 0, 0, 1, 12}, 0},
ans27{4},
},
{
para27{[]int{0, 0, 0, 0, 0}, 0},
ans27{0},
},
{
para27{[]int{1}, 1},
ans27{0},
},
{
para27{[]int{0, 1, 2, 2, 3, 0, 4, 2}, 2},
ans27{5},
},
}
fmt.Printf("------------------------Leetcode Problem 27------------------------\n")
for _, q := range qs {
_, p := q.ans27, q.para27
fmt.Printf("【input】:%v 【output】:%v\n", p.one, removeElement(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/1647.Minimum-Deletions-to-Make-Character-Frequencies-Unique/1647. Minimum Deletions to Make Character Frequencies Unique.go | leetcode/1647.Minimum-Deletions-to-Make-Character-Frequencies-Unique/1647. Minimum Deletions to Make Character Frequencies Unique.go | package leetcode
import (
"sort"
)
func minDeletions(s string) int {
frequency, res := make([]int, 26), 0
for i := 0; i < len(s); i++ {
frequency[s[i]-'a']++
}
sort.Sort(sort.Reverse(sort.IntSlice(frequency)))
for i := 1; i <= 25; i++ {
if frequency[i] == frequency[i-1] && frequency[i] != 0 {
res++
frequency[i]--
sort.Sort(sort.Reverse(sort.IntSlice(frequency)))
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/1647.Minimum-Deletions-to-Make-Character-Frequencies-Unique/1647. Minimum Deletions to Make Character Frequencies Unique_test.go | leetcode/1647.Minimum-Deletions-to-Make-Character-Frequencies-Unique/1647. Minimum Deletions to Make Character Frequencies Unique_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1647 struct {
para1647
ans1647
}
// para 是参数
// one 代表第一个参数
type para1647 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans1647 struct {
one int
}
func Test_Problem1647(t *testing.T) {
qs := []question1647{
{
para1647{"aab"},
ans1647{0},
},
{
para1647{"aaabbbcc"},
ans1647{2},
},
{
para1647{"ceabaacb"},
ans1647{2},
},
{
para1647{""},
ans1647{0},
},
{
para1647{"abcabc"},
ans1647{3},
},
}
fmt.Printf("------------------------Leetcode Problem 1647------------------------\n")
for _, q := range qs {
_, p := q.ans1647, q.para1647
fmt.Printf("【input】:%v 【output】:%v \n", p, minDeletions(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/1189.Maximum-Number-of-Balloons/1189. Maximum Number of Balloons.go | leetcode/1189.Maximum-Number-of-Balloons/1189. Maximum Number of Balloons.go | package leetcode
func maxNumberOfBalloons(text string) int {
fre := make([]int, 26)
for _, t := range text {
fre[t-'a']++
}
// 字符 b 的频次是数组下标 1 对应的元素值
// 字符 a 的频次是数组下标 0 对应的元素值
// 字符 l 的频次是数组下标 11 对应的元素值,这里有 2 个 l,所以元素值需要除以 2
// 字符 o 的频次是数组下标 14 对应的元素值,这里有 2 个 o,所以元素值需要除以 2
// 字符 n 的频次是数组下标 13 对应的元素值
return min(fre[1], min(fre[0], min(fre[11]/2, min(fre[14]/2, fre[13]))))
}
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/1189.Maximum-Number-of-Balloons/1189. Maximum Number of Balloons_test.go | leetcode/1189.Maximum-Number-of-Balloons/1189. Maximum Number of Balloons_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1189 struct {
para1189
ans1189
}
// para 是参数
// one 代表第一个参数
type para1189 struct {
text string
}
// ans 是答案
// one 代表第一个答案
type ans1189 struct {
one int
}
func Test_Problem1189(t *testing.T) {
qs := []question1189{
{
para1189{"nlaebolko"},
ans1189{1},
},
{
para1189{"loonbalxballpoon"},
ans1189{2},
},
{
para1189{"leetcode"},
ans1189{0},
},
}
fmt.Printf("------------------------Leetcode Problem 1189------------------------\n")
for _, q := range qs {
_, p := q.ans1189, q.para1189
fmt.Printf("【input】:%v 【output】:%v\n", p, maxNumberOfBalloons(p.text))
}
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/0189.Rotate-Array/189. Rotate Array_test.go | leetcode/0189.Rotate-Array/189. Rotate Array_test.go | package leetcode
import (
"fmt"
"testing"
)
type question189 struct {
para189
ans189
}
// para 是参数
// one 代表第一个参数
type para189 struct {
nums []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans189 struct {
one []int
}
func Test_Problem189(t *testing.T) {
qs := []question189{
{
para189{[]int{1, 2, 3, 4, 5, 6, 7}, 3},
ans189{[]int{5, 6, 7, 1, 2, 3, 4}},
},
{
para189{[]int{-1, -100, 3, 99}, 2},
ans189{[]int{3, 99, -1, -100}},
},
}
fmt.Printf("------------------------Leetcode Problem 189------------------------\n")
for _, q := range qs {
_, p := q.ans189, q.para189
fmt.Printf("【input】:%v ", p)
rotate(p.nums, p.k)
fmt.Printf("【output】:%v\n", 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/0189.Rotate-Array/189. Rotate Array.go | leetcode/0189.Rotate-Array/189. Rotate Array.go | package leetcode
// 解法一 时间复杂度 O(n),空间复杂度 O(1)
func rotate(nums []int, k int) {
k %= len(nums)
reverse(nums)
reverse(nums[:k])
reverse(nums[k:])
}
func reverse(a []int) {
for i, n := 0, len(a); i < n/2; i++ {
a[i], a[n-1-i] = a[n-1-i], a[i]
}
}
// 解法二 时间复杂度 O(n),空间复杂度 O(n)
func rotate1(nums []int, k int) {
newNums := make([]int, len(nums))
for i, v := range nums {
newNums[(i+k)%len(nums)] = v
}
copy(nums, newNums)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1332.Remove-Palindromic-Subsequences/1332. Remove Palindromic Subsequences.go | leetcode/1332.Remove-Palindromic-Subsequences/1332. Remove Palindromic Subsequences.go | package leetcode
func removePalindromeSub(s string) int {
if len(s) == 0 {
return 0
}
for i := 0; i < len(s)/2; i++ {
if s[i] != s[len(s)-1-i] {
return 2
}
}
return 1
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1332.Remove-Palindromic-Subsequences/1332. Remove Palindromic Subsequences_test.go | leetcode/1332.Remove-Palindromic-Subsequences/1332. Remove Palindromic Subsequences_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1332 struct {
para1332
ans1332
}
// para 是参数
// one 代表第一个参数
type para1332 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans1332 struct {
one int
}
func Test_Problem1332(t *testing.T) {
qs := []question1332{
{
para1332{"ababa"},
ans1332{1},
},
{
para1332{"abb"},
ans1332{2},
},
{
para1332{"baabb"},
ans1332{2},
},
{
para1332{""},
ans1332{0},
},
{
para1332{"bbaabaaa"},
ans1332{2},
},
}
fmt.Printf("------------------------Leetcode Problem 1332------------------------\n")
for _, q := range qs {
_, p := q.ans1332, q.para1332
fmt.Printf("【input】:%v 【output】:%v\n", p, removePalindromeSub(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/0063.Unique-Paths-II/63. Unique Paths II_test.go | leetcode/0063.Unique-Paths-II/63. Unique Paths II_test.go | package leetcode
import (
"fmt"
"testing"
)
type question63 struct {
para63
ans63
}
// para 是参数
// one 代表第一个参数
type para63 struct {
og [][]int
}
// ans 是答案
// one 代表第一个答案
type ans63 struct {
one int
}
func Test_Problem63(t *testing.T) {
qs := []question63{
{
para63{[][]int{
{0, 0, 0},
{0, 1, 0},
{0, 0, 0},
}},
ans63{2},
},
{
para63{[][]int{
{0, 0},
{1, 1},
{0, 0},
}},
ans63{0},
},
{
para63{[][]int{
{0, 1, 0, 0},
{1, 0, 0, 0},
{0, 0, 0, 0},
}},
ans63{0},
},
}
fmt.Printf("------------------------Leetcode Problem 63------------------------\n")
for _, q := range qs {
_, p := q.ans63, q.para63
fmt.Printf("【input】:%v 【output】:%v\n", p, uniquePathsWithObstacles(p.og))
}
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/0063.Unique-Paths-II/63. Unique Paths II.go | leetcode/0063.Unique-Paths-II/63. Unique Paths II.go | package leetcode
func uniquePathsWithObstacles(obstacleGrid [][]int) int {
if len(obstacleGrid) == 0 || obstacleGrid[0][0] == 1 {
return 0
}
m, n := len(obstacleGrid), len(obstacleGrid[0])
dp := make([][]int, m)
for i := 0; i < m; i++ {
dp[i] = make([]int, n)
}
dp[0][0] = 1
for i := 1; i < n; i++ {
if dp[0][i-1] != 0 && obstacleGrid[0][i] != 1 {
dp[0][i] = 1
}
}
for i := 1; i < m; i++ {
if dp[i-1][0] != 0 && obstacleGrid[i][0] != 1 {
dp[i][0] = 1
}
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
if obstacleGrid[i][j] != 1 {
dp[i][j] = dp[i-1][j] + dp[i][j-1]
}
}
}
return dp[m-1][n-1]
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0190.Reverse-Bits/190. Reverse Bits.go | leetcode/0190.Reverse-Bits/190. Reverse Bits.go | package leetcode
func reverseBits(num uint32) uint32 {
var res uint32
for i := 0; i < 32; i++ {
res = res<<1 | num&1
num >>= 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/0190.Reverse-Bits/190. Reverse Bits_test.go | leetcode/0190.Reverse-Bits/190. Reverse Bits_test.go | package leetcode
import (
"fmt"
"strconv"
"testing"
)
type question190 struct {
para190
ans190
}
// para 是参数
// one 代表第一个参数
type para190 struct {
one uint32
}
// ans 是答案
// one 代表第一个答案
type ans190 struct {
one uint32
}
func Test_Problem190(t *testing.T) {
qs := []question190{
{
para190{43261596},
ans190{964176192},
},
{
para190{4294967293},
ans190{3221225471},
},
}
fmt.Printf("------------------------Leetcode Problem 190------------------------\n")
for _, q := range qs {
_, p := q.ans190, q.para190
input := strconv.FormatUint(uint64(p.one), 2) // 32位无符号整数转换为二进制字符串
input = fmt.Sprintf("%0*v", 32, input) // 格式化输出32位,保留前置0
output := reverseBits(p.one)
outputBin := strconv.FormatUint(uint64(output), 2) // 32位无符号整数转换为二进制字符串
outputBin = fmt.Sprintf("%0*v", 32, outputBin) // 格式化输出32位,保留前置0
fmt.Printf("【input】:%v 【output】:%v (%v)\n", input, output, outputBin)
}
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/0996.Number-of-Squareful-Arrays/996. Number of Squareful Arrays.go | leetcode/0996.Number-of-Squareful-Arrays/996. Number of Squareful Arrays.go | package leetcode
import (
"math"
"sort"
)
func numSquarefulPerms(A []int) int {
if len(A) == 0 {
return 0
}
used, p, res := make([]bool, len(A)), []int{}, [][]int{}
sort.Ints(A) // 这里是去重的关键逻辑
generatePermutation996(A, 0, p, &res, &used)
return len(res)
}
func generatePermutation996(nums []int, index int, p []int, res *[][]int, used *[]bool) {
if index == len(nums) {
checkSquareful := true
for i := 0; i < len(p)-1; i++ {
if !checkSquare(p[i] + p[i+1]) {
checkSquareful = false
break
}
}
if checkSquareful {
temp := make([]int, len(p))
copy(temp, p)
*res = append(*res, temp)
}
return
}
for i := 0; i < len(nums); i++ {
if !(*used)[i] {
if i > 0 && nums[i] == nums[i-1] && !(*used)[i-1] { // 这里是去重的关键逻辑
continue
}
if len(p) > 0 && !checkSquare(nums[i]+p[len(p)-1]) { // 关键的剪枝条件
continue
}
(*used)[i] = true
p = append(p, nums[i])
generatePermutation996(nums, index+1, p, res, used)
p = p[:len(p)-1]
(*used)[i] = false
}
}
return
}
func checkSquare(num int) bool {
tmp := math.Sqrt(float64(num))
if int(tmp)*int(tmp) == num {
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/0996.Number-of-Squareful-Arrays/996. Number of Squareful Arrays_test.go | leetcode/0996.Number-of-Squareful-Arrays/996. Number of Squareful Arrays_test.go | package leetcode
import (
"fmt"
"testing"
)
type question996 struct {
para996
ans996
}
// para 是参数
// one 代表第一个参数
type para996 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans996 struct {
one int
}
func Test_Problem996(t *testing.T) {
qs := []question996{
{
para996{[]int{1, 17, 8}},
ans996{2},
},
{
para996{[]int{1}},
ans996{1},
},
{
para996{[]int{2, 2, 2}},
ans996{1},
},
{
para996{[]int{51768, 47861, 48143, 33221, 50893, 56758, 39946, 10312, 20276, 40616, 43633}},
ans996{1},
},
}
fmt.Printf("------------------------Leetcode Problem 996------------------------\n")
for _, q := range qs {
_, p := q.ans996, q.para996
fmt.Printf("【input】:%v 【output】:%v\n", p, numSquarefulPerms(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/0491.Non-decreasing-Subsequences/491. Non-decreasing Subsequences_test.go | leetcode/0491.Non-decreasing-Subsequences/491. Non-decreasing Subsequences_test.go | package leetcode
import (
"fmt"
"testing"
)
type question491 struct {
para491
ans491
}
// para 是参数
// one 代表第一个参数
type para491 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans491 struct {
one [][]int
}
func Test_Problem491(t *testing.T) {
qs := []question491{
{
para491{[]int{4, 3, 2, 1}},
ans491{[][]int{}},
},
{
para491{[]int{4, 6, 7, 7}},
ans491{[][]int{{4, 6}, {4, 7}, {4, 6, 7}, {4, 6, 7, 7}, {6, 7}, {6, 7, 7}, {7, 7}, {4, 7, 7}}},
},
}
fmt.Printf("------------------------Leetcode Problem 491------------------------\n")
for _, q := range qs {
_, p := q.ans491, q.para491
fmt.Printf("【input】:%v 【output】:%v\n", p, findSubsequences(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/0491.Non-decreasing-Subsequences/491. Non-decreasing Subsequences.go | leetcode/0491.Non-decreasing-Subsequences/491. Non-decreasing Subsequences.go | package leetcode
func findSubsequences(nums []int) [][]int {
c, visited, res := []int{}, map[int]bool{}, [][]int{}
for i := 0; i < len(nums)-1; i++ {
if _, ok := visited[nums[i]]; ok {
continue
} else {
visited[nums[i]] = true
generateIncSubsets(nums, i, c, &res)
}
}
return res
}
func generateIncSubsets(nums []int, current int, c []int, res *[][]int) {
c = append(c, nums[current])
if len(c) >= 2 {
b := make([]int, len(c))
copy(b, c)
*res = append(*res, b)
}
visited := map[int]bool{}
for i := current + 1; i < len(nums); i++ {
if nums[current] <= nums[i] {
if _, ok := visited[nums[i]]; ok {
continue
} else {
visited[nums[i]] = true
generateIncSubsets(nums, i, c, res)
}
}
}
c = c[:len(c)-1]
return
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0049.Group-Anagrams/49. Group Anagrams.go | leetcode/0049.Group-Anagrams/49. Group Anagrams.go | package leetcode
import "sort"
type sortRunes []rune
func (s sortRunes) Less(i, j int) bool {
return s[i] < s[j]
}
func (s sortRunes) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s sortRunes) Len() int {
return len(s)
}
func groupAnagrams(strs []string) [][]string {
record, res := map[string][]string{}, [][]string{}
for _, str := range strs {
sByte := []rune(str)
sort.Sort(sortRunes(sByte))
sstrs := record[string(sByte)]
sstrs = append(sstrs, str)
record[string(sByte)] = sstrs
}
for _, v := range record {
res = append(res, v)
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0049.Group-Anagrams/49. Group Anagrams_test.go | leetcode/0049.Group-Anagrams/49. Group Anagrams_test.go | package leetcode
import (
"fmt"
"testing"
)
type question49 struct {
para49
ans49
}
// para 是参数
// one 代表第一个参数
type para49 struct {
one []string
}
// ans 是答案
// one 代表第一个答案
type ans49 struct {
one [][]string
}
func Test_Problem49(t *testing.T) {
qs := []question49{
{
para49{[]string{"eat", "tea", "tan", "ate", "nat", "bat"}},
ans49{[][]string{{"ate", "eat", "tea"}, {"nat", "tan"}, {"bat"}}},
},
}
fmt.Printf("------------------------Leetcode Problem 49------------------------\n")
for _, q := range qs {
_, p := q.ans49, q.para49
fmt.Printf("【input】:%v 【output】:%v\n", p, groupAnagrams(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/1170.Compare-Strings-by-Frequency-of-the-Smallest-Character/1170. Compare Strings by Frequency of the Smallest Character.go | leetcode/1170.Compare-Strings-by-Frequency-of-the-Smallest-Character/1170. Compare Strings by Frequency of the Smallest Character.go | package leetcode
import "sort"
func numSmallerByFrequency(queries []string, words []string) []int {
ws, res := make([]int, len(words)), make([]int, len(queries))
for i, w := range words {
ws[i] = countFunc(w)
}
sort.Ints(ws)
for i, q := range queries {
fq := countFunc(q)
res[i] = len(words) - sort.Search(len(words), func(i int) bool { return fq < ws[i] })
}
return res
}
func countFunc(s string) int {
count, i := [26]int{}, 0
for _, b := range s {
count[b-'a']++
}
for count[i] == 0 {
i++
}
return count[i]
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1170.Compare-Strings-by-Frequency-of-the-Smallest-Character/1170. Compare Strings by Frequency of the Smallest Character_test.go | leetcode/1170.Compare-Strings-by-Frequency-of-the-Smallest-Character/1170. Compare Strings by Frequency of the Smallest Character_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1170 struct {
para1170
ans1170
}
// para 是参数
// one 代表第一个参数
type para1170 struct {
queries []string
words []string
}
// ans 是答案
// one 代表第一个答案
type ans1170 struct {
one []int
}
func Test_Problem1170(t *testing.T) {
qs := []question1170{
{
para1170{[]string{"cbd"}, []string{"zaaaz"}},
ans1170{[]int{1}},
},
{
para1170{[]string{"bbb", "cc"}, []string{"a", "aa", "aaa", "aaaa"}},
ans1170{[]int{1, 2}},
},
}
fmt.Printf("------------------------Leetcode Problem 1170------------------------\n")
for _, q := range qs {
_, p := q.ans1170, q.para1170
fmt.Printf("【input】:%v 【output】:%v\n", p, numSmallerByFrequency(p.queries, 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/0706.Design-HashMap/706. Design HashMap.go | leetcode/0706.Design-HashMap/706. Design HashMap.go | package leetcode
const Len int = 10000
type MyHashMap struct {
content [Len]*HashNode
}
type HashNode struct {
key int
val int
next *HashNode
}
func (N *HashNode) Put(key int, value int) {
if N.key == key {
N.val = value
return
}
if N.next == nil {
N.next = &HashNode{key, value, nil}
return
}
N.next.Put(key, value)
}
func (N *HashNode) Get(key int) int {
if N.key == key {
return N.val
}
if N.next == nil {
return -1
}
return N.next.Get(key)
}
func (N *HashNode) Remove(key int) *HashNode {
if N.key == key {
p := N.next
N.next = nil
return p
}
if N.next != nil {
N.next = N.next.Remove(key)
}
return N
}
/** Initialize your data structure here. */
func Constructor706() MyHashMap {
return MyHashMap{}
}
/** value will always be non-negative. */
func (this *MyHashMap) Put(key int, value int) {
node := this.content[this.Hash(key)]
if node == nil {
this.content[this.Hash(key)] = &HashNode{key: key, val: value, next: nil}
return
}
node.Put(key, value)
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
func (this *MyHashMap) Get(key int) int {
HashNode := this.content[this.Hash(key)]
if HashNode == nil {
return -1
}
return HashNode.Get(key)
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
func (this *MyHashMap) Remove(key int) {
HashNode := this.content[this.Hash(key)]
if HashNode == nil {
return
}
this.content[this.Hash(key)] = HashNode.Remove(key)
}
func (this *MyHashMap) Hash(value int) int {
return value % Len
}
/**
* Your MyHashMap object will be instantiated and called as such:
* obj := Constructor();
* obj.Put(key,value);
* param_2 := obj.Get(key);
* obj.Remove(key);
*/
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0706.Design-HashMap/706. Design HashMap_test.go | leetcode/0706.Design-HashMap/706. Design HashMap_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem706(t *testing.T) {
obj := Constructor706()
obj.Put(7, 10)
fmt.Printf("Get 7 = %v\n", obj.Get(7))
obj.Put(7, 20)
fmt.Printf("Contains 7 = %v\n", obj.Get(7))
param1 := obj.Get(100)
fmt.Printf("param1 = %v\n", param1)
obj.Remove(100007)
param1 = obj.Get(7)
fmt.Printf("param1 = %v\n", param1)
obj.Remove(7)
param1 = obj.Get(7)
fmt.Printf("param1 = %v\n", param1)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0692.Top-K-Frequent-Words/692. Top K Frequent Words.go | leetcode/0692.Top-K-Frequent-Words/692. Top K Frequent Words.go | package leetcode
import "container/heap"
func topKFrequent(words []string, k int) []string {
m := map[string]int{}
for _, word := range words {
m[word]++
}
pq := &PQ{}
heap.Init(pq)
for w, c := range m {
heap.Push(pq, &wordCount{w, c})
if pq.Len() > k {
heap.Pop(pq)
}
}
res := make([]string, k)
for i := k - 1; i >= 0; i-- {
wc := heap.Pop(pq).(*wordCount)
res[i] = wc.word
}
return res
}
type wordCount struct {
word string
cnt int
}
type PQ []*wordCount
func (pq PQ) Len() int { return len(pq) }
func (pq PQ) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] }
func (pq PQ) Less(i, j int) bool {
if pq[i].cnt == pq[j].cnt {
return pq[i].word > pq[j].word
}
return pq[i].cnt < pq[j].cnt
}
func (pq *PQ) Push(x interface{}) {
tmp := x.(*wordCount)
*pq = append(*pq, tmp)
}
func (pq *PQ) Pop() interface{} {
n := len(*pq)
tmp := (*pq)[n-1]
*pq = (*pq)[:n-1]
return tmp
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0692.Top-K-Frequent-Words/692. Top K Frequent Words_test.go | leetcode/0692.Top-K-Frequent-Words/692. Top K Frequent Words_test.go | package leetcode
import (
"fmt"
"testing"
)
type question692 struct {
para692
ans692
}
// para 是参数
// one 代表第一个参数
type para692 struct {
words []string
k int
}
// ans 是答案
// one 代表第一个答案
type ans692 struct {
one []string
}
func Test_Problem692(t *testing.T) {
qs := []question692{
{
para692{[]string{"i", "love", "leetcode", "i", "love", "coding"}, 2},
ans692{[]string{"i", "love"}},
},
{
para692{[]string{"the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"}, 4},
ans692{[]string{"the", "is", "sunny", "day"}},
},
}
fmt.Printf("------------------------Leetcode Problem 692------------------------\n")
for _, q := range qs {
_, p := q.ans692, q.para692
fmt.Printf("【input】:%v 【output】:%v\n", p, topKFrequent(p.words, 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/0535.Encode-and-Decode-TinyURL/535. Encode and Decode TinyURL_test.go | leetcode/0535.Encode-and-Decode-TinyURL/535. Encode and Decode TinyURL_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem535(t *testing.T) {
obj := Constructor()
fmt.Printf("obj = %v\n", obj)
e := obj.encode("https://leetcode.com/problems/design-tinyurl")
fmt.Printf("obj encode = %v\n", e)
d := obj.decode(e)
fmt.Printf("obj decode = %v\n", d)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0535.Encode-and-Decode-TinyURL/535. Encode and Decode TinyURL.go | leetcode/0535.Encode-and-Decode-TinyURL/535. Encode and Decode TinyURL.go | package leetcode
import (
"fmt"
"strconv"
"strings"
)
type Codec struct {
urls []string
}
func Constructor() Codec {
return Codec{[]string{}}
}
// Encodes a URL to a shortened URL.
func (this *Codec) encode(longUrl string) string {
this.urls = append(this.urls, longUrl)
return "http://tinyurl.com/" + fmt.Sprintf("%v", len(this.urls)-1)
}
// Decodes a shortened URL to its original URL.
func (this *Codec) decode(shortUrl string) string {
tmp := strings.Split(shortUrl, "/")
i, _ := strconv.Atoi(tmp[len(tmp)-1])
return this.urls[i]
}
/**
* Your Codec object will be instantiated and called as such:
* obj := Constructor();
* url := obj.encode(longUrl);
* ans := obj.decode(url);
*/
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0473.Matchsticks-to-Square/473. Matchsticks to Square.go | leetcode/0473.Matchsticks-to-Square/473. Matchsticks to Square.go | package leetcode
import "sort"
func makesquare(matchsticks []int) bool {
if len(matchsticks) < 4 {
return false
}
total := 0
for _, v := range matchsticks {
total += v
}
if total%4 != 0 {
return false
}
sort.Slice(matchsticks, func(i, j int) bool {
return matchsticks[i] > matchsticks[j]
})
visited := make([]bool, 16)
return dfs(matchsticks, 0, 0, 0, total, &visited)
}
func dfs(matchsticks []int, cur, group, sum, total int, visited *[]bool) bool {
if group == 4 {
return true
}
if sum > total/4 {
return false
}
if sum == total/4 {
return dfs(matchsticks, 0, group+1, 0, total, visited)
}
last := -1
for i := cur; i < len(matchsticks); i++ {
if (*visited)[i] {
continue
}
if last == matchsticks[i] {
continue
}
(*visited)[i] = true
last = matchsticks[i]
if dfs(matchsticks, i+1, group, sum+matchsticks[i], total, visited) {
return true
}
(*visited)[i] = false
}
return false
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0473.Matchsticks-to-Square/473. Matchsticks to Square_test.go | leetcode/0473.Matchsticks-to-Square/473. Matchsticks to Square_test.go | package leetcode
import (
"fmt"
"testing"
)
type question473 struct {
para473
ans473
}
// para 是参数
// one 代表第一个参数
type para473 struct {
arr []int
}
// ans 是答案
// one 代表第一个答案
type ans473 struct {
one bool
}
func Test_Problem473(t *testing.T) {
qs := []question473{
{
para473{[]int{1, 1, 2, 2, 2}},
ans473{true},
},
{
para473{[]int{3, 3, 3, 3, 4}},
ans473{false},
},
}
fmt.Printf("------------------------Leetcode Problem 473------------------------\n")
for _, q := range qs {
_, p := q.ans473, q.para473
fmt.Printf("【input】:%v 【output】:%v\n", p, makesquare(p.arr))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1455.Check-If-a-Word-Occurs-As-a-Prefix-of-Any-Word-in-a-Sentence/1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence_test.go | leetcode/1455.Check-If-a-Word-Occurs-As-a-Prefix-of-Any-Word-in-a-Sentence/1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1455 struct {
para1455
ans1455
}
// para 是参数
// one 代表第一个参数
type para1455 struct {
sentence string
searchWord string
}
// ans 是答案
// one 代表第一个答案
type ans1455 struct {
one int
}
func Test_Problem1455(t *testing.T) {
qs := []question1455{
{
para1455{"i love eating burger", "burg"},
ans1455{4},
},
{
para1455{"this problem is an easy problem", "pro"},
ans1455{2},
},
{
para1455{"i am tired", "you"},
ans1455{-1},
},
{
para1455{"i use triple pillow", "pill"},
ans1455{4},
},
{
para1455{"hello from the other side", "they"},
ans1455{-1},
},
}
fmt.Printf("------------------------Leetcode Problem 1455------------------------\n")
for _, q := range qs {
_, p := q.ans1455, q.para1455
fmt.Printf("【input】:%v ", p)
fmt.Printf("【output】:%v \n", isPrefixOfWord(p.sentence, p.searchWord))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1455.Check-If-a-Word-Occurs-As-a-Prefix-of-Any-Word-in-a-Sentence/1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence.go | leetcode/1455.Check-If-a-Word-Occurs-As-a-Prefix-of-Any-Word-in-a-Sentence/1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence.go | package leetcode
import "strings"
func isPrefixOfWord(sentence string, searchWord string) int {
for i, v := range strings.Split(sentence, " ") {
if strings.HasPrefix(v, searchWord) {
return i + 1
}
}
return -1
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0523.Continuous-Subarray-Sum/523. Continuous Subarray Sum_test.go | leetcode/0523.Continuous-Subarray-Sum/523. Continuous Subarray Sum_test.go | package leetcode
import (
"fmt"
"testing"
)
type question523 struct {
para523
ans523
}
// para 是参数
// one 代表第一个参数
type para523 struct {
nums []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans523 struct {
one bool
}
func Test_Problem523(t *testing.T) {
qs := []question523{
{
para523{[]int{23, 2, 4, 6, 7}, 6},
ans523{true},
},
{
para523{[]int{23, 2, 6, 4, 7}, 6},
ans523{true},
},
{
para523{[]int{23, 2, 6, 4, 7}, 13},
ans523{false},
},
}
fmt.Printf("------------------------Leetcode Problem 523------------------------\n")
for _, q := range qs {
_, p := q.ans523, q.para523
fmt.Printf("【input】:%v 【output】:%v\n", p, checkSubarraySum(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/0523.Continuous-Subarray-Sum/523. Continuous Subarray Sum.go | leetcode/0523.Continuous-Subarray-Sum/523. Continuous Subarray Sum.go | package leetcode
func checkSubarraySum(nums []int, k int) bool {
m := make(map[int]int)
m[0] = -1
sum := 0
for i, n := range nums {
sum += n
if r, ok := m[sum%k]; ok {
if i-2 >= r {
return true
}
} else {
m[sum%k] = i
}
}
return false
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0412.Fizz-Buzz/412. Fizz Buzz.go | leetcode/0412.Fizz-Buzz/412. Fizz Buzz.go | package leetcode
import "strconv"
func fizzBuzz(n int) []string {
solution := make([]string, n)
for i := 1; i <= n; i++ {
solution[i-1] = ""
if i%3 == 0 {
solution[i-1] += "Fizz"
}
if i%5 == 0 {
solution[i-1] += "Buzz"
}
if solution[i-1] == "" {
solution[i-1] = strconv.Itoa(i)
}
}
return solution
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0412.Fizz-Buzz/412. Fizz Buzz_test.go | leetcode/0412.Fizz-Buzz/412. Fizz Buzz_test.go | package leetcode
import (
"fmt"
"testing"
)
var tcs = []struct {
n int
ans []string
}{
{
15,
[]string{
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz",
},
},
}
func Test_fizzBuzz(t *testing.T) {
fmt.Printf("------------------------Leetcode Problem 412------------------------\n")
for _, tc := range tcs {
fmt.Printf("【output】:%v\n", tc)
}
fmt.Printf("\n\n\n")
}
func Benchmark_fizzBuzz(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range tcs {
fizzBuzz(tc.n)
}
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/9990975.Odd-Even-Jump/975. Odd Even Jump.go | leetcode/9990975.Odd-Even-Jump/975. Odd Even Jump.go | package leetcode
import (
"fmt"
)
func oddEvenJumps(A []int) int {
oddJumpMap, evenJumpMap, current, res := map[int]int{}, map[int]int{}, 0, 0
for i := 0; i < len(A); i++ {
for j := i + 1; j < len(A); j++ {
if v, ok := oddJumpMap[i]; ok {
if A[i] <= A[j] && A[j] <= A[v] {
if A[j] == A[v] && j < oddJumpMap[i] {
oddJumpMap[i] = j
} else if A[j] < A[v] {
oddJumpMap[i] = j
}
}
} else {
if A[i] <= A[j] {
oddJumpMap[i] = j
}
}
}
}
for i := 0; i < len(A); i++ {
for j := i + 1; j < len(A); j++ {
if v, ok := evenJumpMap[i]; ok {
if A[i] >= A[j] && A[j] >= A[v] {
if A[j] == A[v] && j < evenJumpMap[i] {
evenJumpMap[i] = j
} else if A[j] > A[v] {
evenJumpMap[i] = j
}
}
} else {
if A[i] >= A[j] {
evenJumpMap[i] = j
}
}
}
}
fmt.Printf("oddJumpMap = %v evenJumpMap = %v\n", oddJumpMap, evenJumpMap)
for i := 0; i < len(A); i++ {
count := 1
current = i
for {
if count%2 == 1 {
if v, ok := oddJumpMap[current]; ok {
if v == len(A)-1 {
res++
break
}
current = v
count++
} else {
break
}
}
if count%2 == 0 {
if v, ok := evenJumpMap[current]; ok {
if v == len(A)-1 {
res++
break
}
current = v
count++
} else {
break
}
}
}
}
return res + 1
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/9990975.Odd-Even-Jump/975. Odd Even Jump_test.go | leetcode/9990975.Odd-Even-Jump/975. Odd Even Jump_test.go | package leetcode
import (
"fmt"
"testing"
)
type question975 struct {
para975
ans975
}
// para 是参数
// one 代表第一个参数
type para975 struct {
A []int
}
// ans 是答案
// one 代表第一个答案
type ans975 struct {
one int
}
func Test_Problem975(t *testing.T) {
qs := []question975{
{
para975{[]int{10, 13, 12, 14, 15}},
ans975{2},
},
{
para975{[]int{2, 3, 1, 1, 4}},
ans975{3},
},
{
para975{[]int{5, 1, 3, 4, 2}},
ans975{3},
},
}
fmt.Printf("------------------------Leetcode Problem 975------------------------\n")
for _, q := range qs {
_, p := q.ans975, q.para975
fmt.Printf("【input】:%v 【output】:%v\n", p, oddEvenJumps(p.A))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0942.DI-String-Match/942. DI String Match_test.go | leetcode/0942.DI-String-Match/942. DI String Match_test.go | package leetcode
import (
"fmt"
"testing"
)
type question942 struct {
para942
ans942
}
// para 是参数
// one 代表第一个参数
type para942 struct {
S string
}
// ans 是答案
// one 代表第一个答案
type ans942 struct {
one []int
}
func Test_Problem942(t *testing.T) {
qs := []question942{
{
para942{"IDID"},
ans942{[]int{0, 4, 1, 3, 2}},
},
{
para942{"III"},
ans942{[]int{0, 1, 2, 3}},
},
{
para942{"DDI"},
ans942{[]int{3, 2, 0, 1}},
},
}
fmt.Printf("------------------------Leetcode Problem 942------------------------\n")
for _, q := range qs {
_, p := q.ans942, q.para942
fmt.Printf("【input】:%v 【output】:%v\n", p, diStringMatch(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/0942.DI-String-Match/942. DI String Match.go | leetcode/0942.DI-String-Match/942. DI String Match.go | package leetcode
func diStringMatch(S string) []int {
result, maxNum, minNum, index := make([]int, len(S)+1), len(S), 0, 0
for _, ch := range S {
if ch == 'I' {
result[index] = minNum
minNum++
} else {
result[index] = maxNum
maxNum--
}
index++
}
result[index] = minNum
return result
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0907.Sum-of-Subarray-Minimums/907. Sum of Subarray Minimums_test.go | leetcode/0907.Sum-of-Subarray-Minimums/907. Sum of Subarray Minimums_test.go | package leetcode
import (
"fmt"
"testing"
)
type question907 struct {
para907
ans907
}
// para 是参数
// one 代表第一个参数
type para907 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans907 struct {
one int
}
func Test_Problem907(t *testing.T) {
qs := []question907{
{
para907{[]int{3, 1, 2, 4}},
ans907{17},
},
}
fmt.Printf("------------------------Leetcode Problem 907------------------------\n")
for _, q := range qs {
_, p := q.ans907, q.para907
fmt.Printf("【input】:%v 【output】:%v\n", p, sumSubarrayMins(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/0907.Sum-of-Subarray-Minimums/907. Sum of Subarray Minimums.go | leetcode/0907.Sum-of-Subarray-Minimums/907. Sum of Subarray Minimums.go | package leetcode
// 解法一 最快的解是 DP + 单调栈
func sumSubarrayMins(A []int) int {
stack, dp, res, mod := []int{}, make([]int, len(A)+1), 0, 1000000007
stack = append(stack, -1)
for i := 0; i < len(A); i++ {
for stack[len(stack)-1] != -1 && A[i] <= A[stack[len(stack)-1]] {
stack = stack[:len(stack)-1]
}
dp[i+1] = (dp[stack[len(stack)-1]+1] + (i-stack[len(stack)-1])*A[i]) % mod
stack = append(stack, i)
res += dp[i+1]
res %= mod
}
return res
}
type pair struct {
val int
count int
}
// 解法二 用两个单调栈
func sumSubarrayMins1(A []int) int {
res, n, mod := 0, len(A), 1000000007
lefts, rights, leftStack, rightStack := make([]int, n), make([]int, n), []*pair{}, []*pair{}
for i := 0; i < n; i++ {
count := 1
for len(leftStack) != 0 && leftStack[len(leftStack)-1].val > A[i] {
count += leftStack[len(leftStack)-1].count
leftStack = leftStack[:len(leftStack)-1]
}
leftStack = append(leftStack, &pair{val: A[i], count: count})
lefts[i] = count
}
for i := n - 1; i >= 0; i-- {
count := 1
for len(rightStack) != 0 && rightStack[len(rightStack)-1].val >= A[i] {
count += rightStack[len(rightStack)-1].count
rightStack = rightStack[:len(rightStack)-1]
}
rightStack = append(rightStack, &pair{val: A[i], count: count})
rights[i] = count
}
for i := 0; i < n; i++ {
res = (res + A[i]*lefts[i]*rights[i]) % mod
}
return res
}
// 解法三 暴力解法,中间很多重复判断子数组的情况
func sumSubarrayMins2(A []int) int {
res, mod := 0, 1000000007
for i := 0; i < len(A); i++ {
stack := []int{}
stack = append(stack, A[i])
for j := i; j < len(A); j++ {
if stack[len(stack)-1] >= A[j] {
stack = stack[:len(stack)-1]
stack = append(stack, A[j])
}
res += stack[len(stack)-1]
}
}
return res % mod
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0503.Next-Greater-Element-II/503. Next Greater Element II.go | leetcode/0503.Next-Greater-Element-II/503. Next Greater Element II.go | package leetcode
// 解法一 单调栈
func nextGreaterElements(nums []int) []int {
res := make([]int, 0)
indexes := make([]int, 0)
for i := 0; i < len(nums); i++ {
res = append(res, -1)
}
for i := 0; i < len(nums)*2; i++ {
num := nums[i%len(nums)]
for len(indexes) > 0 && nums[indexes[len(indexes)-1]] < num {
index := indexes[len(indexes)-1]
res[index] = num
indexes = indexes[:len(indexes)-1]
}
indexes = append(indexes, i%len(nums))
}
return res
}
// 解法二
func nextGreaterElements1(nums []int) []int {
if len(nums) == 0 {
return []int{}
}
res := []int{}
for i := 0; i < len(nums); i++ {
j, find := (i+1)%len(nums), false
for j != i {
if nums[j] > nums[i] {
find = true
res = append(res, nums[j])
break
}
j = (j + 1) % len(nums)
}
if !find {
res = append(res, -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/0503.Next-Greater-Element-II/503. Next Greater Element II_test.go | leetcode/0503.Next-Greater-Element-II/503. Next Greater Element II_test.go | package leetcode
import (
"fmt"
"testing"
)
type question503 struct {
para503
ans503
}
// para 是参数
// one 代表第一个参数
type para503 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans503 struct {
one []int
}
func Test_Problem503(t *testing.T) {
qs := []question503{
{
para503{[]int{}},
ans503{[]int{}},
},
{
para503{[]int{1}},
ans503{[]int{-1}},
},
{
para503{[]int{1, 2, 1}},
ans503{[]int{2, -1, 2}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 503------------------------\n")
for _, q := range qs {
_, p := q.ans503, q.para503
fmt.Printf("【input】:%v 【output】:%v\n", p, nextGreaterElements(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/0018.4Sum/18. 4Sum.go | leetcode/0018.4Sum/18. 4Sum.go | package leetcode
import "sort"
// 解法一 双指针
func fourSum(nums []int, target int) (quadruplets [][]int) {
sort.Ints(nums)
n := len(nums)
for i := 0; i < n-3 && nums[i]+nums[i+1]+nums[i+2]+nums[i+3] <= target; i++ {
if i > 0 && nums[i] == nums[i-1] || nums[i]+nums[n-3]+nums[n-2]+nums[n-1] < target {
continue
}
for j := i + 1; j < n-2 && nums[i]+nums[j]+nums[j+1]+nums[j+2] <= target; j++ {
if j > i+1 && nums[j] == nums[j-1] || nums[i]+nums[j]+nums[n-2]+nums[n-1] < target {
continue
}
for left, right := j+1, n-1; left < right; {
if sum := nums[i] + nums[j] + nums[left] + nums[right]; sum == target {
quadruplets = append(quadruplets, []int{nums[i], nums[j], nums[left], nums[right]})
for left++; left < right && nums[left] == nums[left-1]; left++ {
}
for right--; left < right && nums[right] == nums[right+1]; right-- {
}
} else if sum < target {
left++
} else {
right--
}
}
}
}
return
}
// 解法二 kSum
func fourSum1(nums []int, target int) [][]int {
res, cur := make([][]int, 0), make([]int, 0)
sort.Ints(nums)
kSum(nums, 0, len(nums)-1, target, 4, cur, &res)
return res
}
func kSum(nums []int, left, right int, target int, k int, cur []int, res *[][]int) {
if right-left+1 < k || k < 2 || target < nums[left]*k || target > nums[right]*k {
return
}
if k == 2 {
// 2 sum
twoSum(nums, left, right, target, cur, res)
} else {
for i := left; i < len(nums); i++ {
if i == left || (i > left && nums[i-1] != nums[i]) {
next := make([]int, len(cur))
copy(next, cur)
next = append(next, nums[i])
kSum(nums, i+1, len(nums)-1, target-nums[i], k-1, next, res)
}
}
}
}
func twoSum(nums []int, left, right int, target int, cur []int, res *[][]int) {
for left < right {
sum := nums[left] + nums[right]
if sum == target {
cur = append(cur, nums[left], nums[right])
temp := make([]int, len(cur))
copy(temp, cur)
*res = append(*res, temp)
// reset cur to previous state
cur = cur[:len(cur)-2]
left++
right--
for left < right && nums[left] == nums[left-1] {
left++
}
for left < right && nums[right] == nums[right+1] {
right--
}
} else if sum < target {
left++
} else {
right--
}
}
}
// 解法三
func fourSum2(nums []int, target int) [][]int {
res := [][]int{}
counter := map[int]int{}
for _, value := range nums {
counter[value]++
}
uniqNums := []int{}
for key := range counter {
uniqNums = append(uniqNums, key)
}
sort.Ints(uniqNums)
for i := 0; i < len(uniqNums); i++ {
if (uniqNums[i]*4 == target) && counter[uniqNums[i]] >= 4 {
res = append(res, []int{uniqNums[i], uniqNums[i], uniqNums[i], uniqNums[i]})
}
for j := i + 1; j < len(uniqNums); j++ {
if (uniqNums[i]*3+uniqNums[j] == target) && counter[uniqNums[i]] > 2 {
res = append(res, []int{uniqNums[i], uniqNums[i], uniqNums[i], uniqNums[j]})
}
if (uniqNums[j]*3+uniqNums[i] == target) && counter[uniqNums[j]] > 2 {
res = append(res, []int{uniqNums[i], uniqNums[j], uniqNums[j], uniqNums[j]})
}
if (uniqNums[j]*2+uniqNums[i]*2 == target) && counter[uniqNums[j]] > 1 && counter[uniqNums[i]] > 1 {
res = append(res, []int{uniqNums[i], uniqNums[i], uniqNums[j], uniqNums[j]})
}
for k := j + 1; k < len(uniqNums); k++ {
if (uniqNums[i]*2+uniqNums[j]+uniqNums[k] == target) && counter[uniqNums[i]] > 1 {
res = append(res, []int{uniqNums[i], uniqNums[i], uniqNums[j], uniqNums[k]})
}
if (uniqNums[j]*2+uniqNums[i]+uniqNums[k] == target) && counter[uniqNums[j]] > 1 {
res = append(res, []int{uniqNums[i], uniqNums[j], uniqNums[j], uniqNums[k]})
}
if (uniqNums[k]*2+uniqNums[i]+uniqNums[j] == target) && counter[uniqNums[k]] > 1 {
res = append(res, []int{uniqNums[i], uniqNums[j], uniqNums[k], uniqNums[k]})
}
c := target - uniqNums[i] - uniqNums[j] - uniqNums[k]
if c > uniqNums[k] && counter[c] > 0 {
res = append(res, []int{uniqNums[i], uniqNums[j], uniqNums[k], c})
}
}
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0018.4Sum/18. 4Sum_test.go | leetcode/0018.4Sum/18. 4Sum_test.go | package leetcode
import (
"fmt"
"testing"
)
type question18 struct {
para18
ans18
}
// para 是参数
// one 代表第一个参数
type para18 struct {
a []int
t int
}
// ans 是答案
// one 代表第一个答案
type ans18 struct {
one [][]int
}
func Test_Problem18(t *testing.T) {
qs := []question18{
{
para18{[]int{1, 1, 1, 1}, 4},
ans18{[][]int{{1, 1, 1, 1}}},
},
{
para18{[]int{0, 1, 5, 0, 1, 5, 5, -4}, 11},
ans18{[][]int{{-4, 5, 5, 5}, {0, 1, 5, 5}}},
},
{
para18{[]int{1, 0, -1, 0, -2, 2}, 0},
ans18{[][]int{{-1, 0, 0, 1}, {-2, -1, 1, 2}, {-2, 0, 0, 2}}},
},
{
para18{[]int{1, 0, -1, 0, -2, 2, 0, 0, 0, 0}, 0},
ans18{[][]int{{-1, 0, 0, 1}, {-2, -1, 1, 2}, {-2, 0, 0, 2}, {0, 0, 0, 0}}},
},
{
para18{[]int{1, 0, -1, 0, -2, 2, 0, 0, 0, 0}, 1},
ans18{[][]int{{-1, 0, 0, 2}, {-2, 0, 1, 2}, {0, 0, 0, 1}}},
},
}
fmt.Printf("------------------------Leetcode Problem 18------------------------\n")
for _, q := range qs {
_, p := q.ans18, q.para18
fmt.Printf("【input】:%v 【output】:%v\n", p, fourSum(p.a, p.t))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0043.Multiply-Strings/43. Multiply Strings_test.go | leetcode/0043.Multiply-Strings/43. Multiply Strings_test.go | package leetcode
import (
"fmt"
"testing"
)
type question43 struct {
para43
ans43
}
// para 是参数
// one 代表第一个参数
type para43 struct {
num1 string
num2 string
}
// ans 是答案
// one 代表第一个答案
type ans43 struct {
one string
}
func Test_Problem43(t *testing.T) {
qs := []question43{
{
para43{"2", "3"},
ans43{"6"},
},
{
para43{"123", "456"},
ans43{"56088"},
},
}
fmt.Printf("------------------------Leetcode Problem 43------------------------\n")
for _, q := range qs {
_, p := q.ans43, q.para43
fmt.Printf("【input】:%v 【output】:%v\n", p, multiply(p.num1, p.num2))
}
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/0043.Multiply-Strings/43. Multiply Strings.go | leetcode/0043.Multiply-Strings/43. Multiply Strings.go | package leetcode
func multiply(num1 string, num2 string) string {
if num1 == "0" || num2 == "0" {
return "0"
}
b1, b2, tmp := []byte(num1), []byte(num2), make([]int, len(num1)+len(num2))
for i := 0; i < len(b1); i++ {
for j := 0; j < len(b2); j++ {
tmp[i+j+1] += int(b1[i]-'0') * int(b2[j]-'0')
}
}
for i := len(tmp) - 1; i > 0; i-- {
tmp[i-1] += tmp[i] / 10
tmp[i] = tmp[i] % 10
}
if tmp[0] == 0 {
tmp = tmp[1:]
}
res := make([]byte, len(tmp))
for i := 0; i < len(tmp); i++ {
res[i] = '0' + byte(tmp[i])
}
return string(res)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0053.Maximum-Subarray/53. Maximum Subarray_test.go | leetcode/0053.Maximum-Subarray/53. Maximum Subarray_test.go | package leetcode
import (
"fmt"
"testing"
)
type question53 struct {
para53
ans53
}
// para 是参数
// one 代表第一个参数
type para53 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans53 struct {
one int
}
func Test_Problem53(t *testing.T) {
qs := []question53{
{
para53{[]int{-2, 1, -3, 4, -1, 2, 1, -5, 4}},
ans53{6},
},
{
para53{[]int{2, 7, 9, 3, 1}},
ans53{22},
},
{
para53{[]int{2}},
ans53{2},
},
{
para53{[]int{-1, -2}},
ans53{-1},
},
}
fmt.Printf("------------------------Leetcode Problem 53------------------------\n")
for _, q := range qs {
_, p := q.ans53, q.para53
fmt.Printf("【input】:%v 【output】:%v\n", p, maxSubArray(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/0053.Maximum-Subarray/53. Maximum Subarray.go | leetcode/0053.Maximum-Subarray/53. Maximum Subarray.go | package leetcode
// 解法一 DP
func maxSubArray(nums []int) int {
if len(nums) == 0 {
return 0
}
if len(nums) == 1 {
return nums[0]
}
dp, res := make([]int, len(nums)), nums[0]
dp[0] = nums[0]
for i := 1; i < len(nums); i++ {
if dp[i-1] > 0 {
dp[i] = nums[i] + dp[i-1]
} else {
dp[i] = nums[i]
}
res = max(res, dp[i])
}
return res
}
// 解法二 模拟
func maxSubArray1(nums []int) int {
if len(nums) == 1 {
return nums[0]
}
maxSum, res, p := nums[0], 0, 0
for p < len(nums) {
res += nums[p]
if res > maxSum {
maxSum = res
}
if res < 0 {
res = 0
}
p++
}
return maxSum
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
| 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.