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/0404.Sum-of-Left-Leaves/404. Sum of Left Leaves_test.go | leetcode/0404.Sum-of-Left-Leaves/404. Sum of Left Leaves_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question404 struct {
para404
ans404
}
// para 是参数
// one 代表第一个参数
type para404 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans404 struct {
one int
}
func Test_Problem404(t *testing.T) {
qs := []question404{
{
para404{[]int{}},
ans404{0},
},
{
para404{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}},
ans404{24},
},
}
fmt.Printf("------------------------Leetcode Problem 404------------------------\n")
for _, q := range qs {
_, p := q.ans404, q.para404
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", sumOfLeftLeaves(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/0404.Sum-of-Left-Leaves/404. Sum of Left Leaves.go | leetcode/0404.Sum-of-Left-Leaves/404. Sum of Left Leaves.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 sumOfLeftLeaves(root *TreeNode) int {
if root == nil {
return 0
}
if root.Left != nil && root.Left.Left == nil && root.Left.Right == nil {
return root.Left.Val + sumOfLeftLeaves(root.Right)
}
return sumOfLeftLeaves(root.Left) + sumOfLeftLeaves(root.Right)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0164.Maximum-Gap/164. Maximum Gap_test.go | leetcode/0164.Maximum-Gap/164. Maximum Gap_test.go | package leetcode
import (
"fmt"
"testing"
)
type question164 struct {
para164
ans164
}
// para 是参数
// one 代表第一个参数
type para164 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans164 struct {
one int
}
func Test_Problem164(t *testing.T) {
qs := []question164{
{
para164{[]int{3, 6, 9, 1}},
ans164{3},
},
{
para164{[]int{1}},
ans164{0},
},
{
para164{[]int{}},
ans164{0},
},
{
para164{[]int{2, 10}},
ans164{8},
},
{
para164{[]int{2, 435, 214, 64321, 643, 7234, 7, 436523, 7856, 8}},
ans164{372202},
},
{
para164{[]int{1, 10000000}},
ans164{9999999},
},
}
fmt.Printf("------------------------Leetcode Problem 164------------------------\n")
for _, q := range qs {
_, p := q.ans164, q.para164
fmt.Printf("【input】:%v 【output】:%v\n", p, maximumGap1(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/0164.Maximum-Gap/164. Maximum Gap.go | leetcode/0164.Maximum-Gap/164. Maximum Gap.go | package leetcode
// 解法一 快排
func maximumGap(nums []int) int {
if len(nums) < 2 {
return 0
}
quickSort164(nums, 0, len(nums)-1)
res := 0
for i := 0; i < len(nums)-1; i++ {
if (nums[i+1] - nums[i]) > res {
res = nums[i+1] - nums[i]
}
}
return res
}
func partition164(a []int, lo, hi int) int {
pivot := a[hi]
i := lo - 1
for j := lo; j < hi; j++ {
if a[j] < pivot {
i++
a[j], a[i] = a[i], a[j]
}
}
a[i+1], a[hi] = a[hi], a[i+1]
return i + 1
}
func quickSort164(a []int, lo, hi int) {
if lo >= hi {
return
}
p := partition164(a, lo, hi)
quickSort164(a, lo, p-1)
quickSort164(a, p+1, hi)
}
// 解法二 基数排序
func maximumGap1(nums []int) int {
if nums == nil || len(nums) < 2 {
return 0
}
// m is the maximal number in nums
m := nums[0]
for i := 1; i < len(nums); i++ {
m = max(m, nums[i])
}
exp := 1 // 1, 10, 100, 1000 ...
R := 10 // 10 digits
aux := make([]int, len(nums))
for (m / exp) > 0 { // Go through all digits from LSB to MSB
count := make([]int, R)
for i := 0; i < len(nums); i++ {
count[(nums[i]/exp)%10]++
}
for i := 1; i < len(count); i++ {
count[i] += count[i-1]
}
for i := len(nums) - 1; i >= 0; i-- {
tmp := count[(nums[i]/exp)%10]
tmp--
aux[tmp] = nums[i]
count[(nums[i]/exp)%10] = tmp
}
for i := 0; i < len(nums); i++ {
nums[i] = aux[i]
}
exp *= 10
}
maxValue := 0
for i := 1; i < len(aux); i++ {
maxValue = max(maxValue, aux[i]-aux[i-1])
}
return maxValue
}
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/1684.Count-the-Number-of-Consistent-Strings/1684. Count the Number of Consistent Strings.go | leetcode/1684.Count-the-Number-of-Consistent-Strings/1684. Count the Number of Consistent Strings.go | package leetcode
func countConsistentStrings(allowed string, words []string) int {
allowedMap, res, flag := map[rune]int{}, 0, true
for _, str := range allowed {
allowedMap[str]++
}
for i := 0; i < len(words); i++ {
flag = true
for j := 0; j < len(words[i]); j++ {
if _, ok := allowedMap[rune(words[i][j])]; !ok {
flag = false
break
}
}
if flag {
res++
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1684.Count-the-Number-of-Consistent-Strings/1684. Count the Number of Consistent Strings_test.go | leetcode/1684.Count-the-Number-of-Consistent-Strings/1684. Count the Number of Consistent Strings_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1684 struct {
para1684
ans1684
}
// para 是参数
// one 代表第一个参数
type para1684 struct {
allowed string
words []string
}
// ans 是答案
// one 代表第一个答案
type ans1684 struct {
one int
}
func Test_Problem1684(t *testing.T) {
qs := []question1684{
{
para1684{"ab", []string{"ad", "bd", "aaab", "baa", "badab"}},
ans1684{2},
},
{
para1684{"abc", []string{"a", "b", "c", "ab", "ac", "bc", "abc"}},
ans1684{7},
},
{
para1684{"cad", []string{"cc", "acd", "b", "ba", "bac", "bad", "ac", "d"}},
ans1684{4},
},
}
fmt.Printf("------------------------Leetcode Problem 1684------------------------\n")
for _, q := range qs {
_, p := q.ans1684, q.para1684
fmt.Printf("【input】:%v 【output】:%v\n", p, countConsistentStrings(p.allowed, 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/1202.Smallest-String-With-Swaps/1202. Smallest String With Swaps.go | leetcode/1202.Smallest-String-With-Swaps/1202. Smallest String With Swaps.go | package leetcode
import (
"sort"
"github.com/halfrost/LeetCode-Go/template"
)
func smallestStringWithSwaps(s string, pairs [][]int) string {
uf, res, sMap := template.UnionFind{}, []byte(s), map[int][]byte{}
uf.Init(len(s))
for _, pair := range pairs {
uf.Union(pair[0], pair[1])
}
for i := 0; i < len(s); i++ {
r := uf.Find(i)
sMap[r] = append(sMap[r], s[i])
}
for _, v := range sMap {
sort.Slice(v, func(i, j int) bool {
return v[i] < v[j]
})
}
for i := 0; i < len(s); i++ {
r := uf.Find(i)
bytes := sMap[r]
res[i] = bytes[0]
sMap[r] = bytes[1:]
}
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/1202.Smallest-String-With-Swaps/1202. Smallest String With Swaps_test.go | leetcode/1202.Smallest-String-With-Swaps/1202. Smallest String With Swaps_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1202 struct {
para1202
ans1202
}
// para 是参数
// one 代表第一个参数
type para1202 struct {
s string
pairs [][]int
}
// ans 是答案
// one 代表第一个答案
type ans1202 struct {
one string
}
func Test_Problem1202(t *testing.T) {
qs := []question1202{
{
para1202{"dcab", [][]int{{0, 3}, {1, 2}}},
ans1202{"bacd"},
},
{
para1202{"dcab", [][]int{{0, 3}, {1, 2}, {0, 2}}},
ans1202{"abcd"},
},
{
para1202{"cba", [][]int{{0, 1}, {1, 2}}},
ans1202{"abc"},
},
}
fmt.Printf("------------------------Leetcode Problem 1202------------------------\n")
for _, q := range qs {
_, p := q.ans1202, q.para1202
fmt.Printf("【input】:%v 【output】:%v\n", p, smallestStringWithSwaps(p.s, p.pairs))
}
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/1093.Statistics-from-a-Large-Sample/1093. Statistics from a Large Sample_test.go | leetcode/1093.Statistics-from-a-Large-Sample/1093. Statistics from a Large Sample_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1093 struct {
para1093
ans1093
}
// para 是参数
// one 代表第一个参数
type para1093 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans1093 struct {
one []float64
}
func Test_Problem1093(t *testing.T) {
qs := []question1093{
{
para1093{[]int{0, 1, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
ans1093{[]float64{1.00000, 3.00000, 2.37500, 2.50000, 3.00000}},
},
{
para1093{[]int{0, 4, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
ans1093{[]float64{1.00000, 4.00000, 2.18182, 2.00000, 1.00000}},
},
}
fmt.Printf("------------------------Leetcode Problem 1093------------------------\n")
for _, q := range qs {
_, p := q.ans1093, q.para1093
fmt.Printf("【input】:%v 【output】:%v\n", p, sampleStats(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/1093.Statistics-from-a-Large-Sample/1093. Statistics from a Large Sample.go | leetcode/1093.Statistics-from-a-Large-Sample/1093. Statistics from a Large Sample.go | package leetcode
func sampleStats(count []int) []float64 {
res := make([]float64, 5)
res[0] = 255
sum := 0
for _, val := range count {
sum += val
}
left, right := sum/2, sum/2
if (sum % 2) == 0 {
right++
}
pre, mode := 0, 0
for i, val := range count {
if val > 0 {
if i < int(res[0]) {
res[0] = float64(i)
}
res[1] = float64(i)
}
res[2] += float64(i*val) / float64(sum)
if pre < left && pre+val >= left {
res[3] += float64(i) / 2.0
}
if pre < right && pre+val >= right {
res[3] += float64(i) / 2.0
}
pre += val
if val > mode {
mode = val
res[4] = float64(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/1721.Swapping-Nodes-in-a-Linked-List/1721. Swapping Nodes in a Linked List_test.go | leetcode/1721.Swapping-Nodes-in-a-Linked-List/1721. Swapping Nodes in a Linked List_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question2 struct {
para2
ans2
}
// para 是参数
// one 代表第一个参数
type para2 struct {
head []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans2 struct {
one []int
}
func Test_Problem2(t *testing.T) {
qs := []question2{
{
para2{[]int{1, 2, 3, 4, 5}, 2},
ans2{[]int{1, 4, 3, 2, 5}},
},
{
para2{[]int{7, 9, 6, 6, 7, 8, 3, 0, 9, 5}, 5},
ans2{[]int{7, 9, 6, 6, 8, 7, 3, 0, 9, 5}},
},
{
para2{[]int{1}, 1},
ans2{[]int{1}},
},
{
para2{[]int{1, 2}, 1},
ans2{[]int{2, 1}},
},
{
para2{[]int{1, 2, 3}, 2},
ans2{[]int{1, 2, 3}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 2------------------------\n")
for _, q := range qs {
_, p := q.ans2, q.para2
fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(swapNodes(structures.Ints2List(p.head), 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/1721.Swapping-Nodes-in-a-Linked-List/1721. Swapping Nodes in a Linked List.go | leetcode/1721.Swapping-Nodes-in-a-Linked-List/1721. Swapping Nodes in a Linked List.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// ListNode define
type ListNode = structures.ListNode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func swapNodes(head *ListNode, k int) *ListNode {
count := 1
var a, b *ListNode
for node := head; node != nil; node = node.Next {
if count == k {
a = node
}
count++
}
length := count
count = 1
for node := head; node != nil; node = node.Next {
if count == length-k {
b = node
}
count++
}
a.Val, b.Val = b.Val, a.Val
return head
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1208.Get-Equal-Substrings-Within-Budget/1208. Get Equal Substrings Within Budget.go | leetcode/1208.Get-Equal-Substrings-Within-Budget/1208. Get Equal Substrings Within Budget.go | package leetcode
func equalSubstring(s string, t string, maxCost int) int {
left, right, res := 0, -1, 0
for left < len(s) {
if right+1 < len(s) && maxCost-abs(int(s[right+1]-'a')-int(t[right+1]-'a')) >= 0 {
right++
maxCost -= abs(int(s[right]-'a') - int(t[right]-'a'))
} else {
res = max(res, right-left+1)
maxCost += abs(int(s[left]-'a') - int(t[left]-'a'))
left++
}
}
return res
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
func abs(a int) int {
if a > 0 {
return a
}
return -a
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1208.Get-Equal-Substrings-Within-Budget/1208. Get Equal Substrings Within Budget_test.go | leetcode/1208.Get-Equal-Substrings-Within-Budget/1208. Get Equal Substrings Within Budget_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1208 struct {
para1208
ans1208
}
// para 是参数
// one 代表第一个参数
type para1208 struct {
s string
t string
maxCost int
}
// ans 是答案
// one 代表第一个答案
type ans1208 struct {
one int
}
func Test_Problem1208(t *testing.T) {
qs := []question1208{
{
para1208{"abcd", "bcdf", 3},
ans1208{3},
},
{
para1208{"abcd", "cdef", 3},
ans1208{1},
},
{
para1208{"abcd", "acde", 0},
ans1208{1},
},
{
para1208{"thjdoffka", "qhrnlntls", 11},
ans1208{3},
},
{
para1208{"krrgw", "zjxss", 19},
ans1208{2},
},
}
fmt.Printf("------------------------Leetcode Problem 1208------------------------\n")
for _, q := range qs {
_, p := q.ans1208, q.para1208
fmt.Printf("【input】:%v 【output】:%v\n", p, equalSubstring(p.s, p.t, p.maxCost))
}
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/0402.Remove-K-Digits/402. Remove K Digits_test.go | leetcode/0402.Remove-K-Digits/402. Remove K Digits_test.go | package leetcode
import (
"fmt"
"testing"
)
type question402 struct {
para402
ans402
}
// para 是参数
// one 代表第一个参数
type para402 struct {
num string
k int
}
// ans 是答案
// one 代表第一个答案
type ans402 struct {
one string
}
func Test_Problem402(t *testing.T) {
qs := []question402{
{
para402{"10", 1},
ans402{"0"},
},
{
para402{"1111111", 3},
ans402{"1111"},
},
{
para402{"5337", 2},
ans402{"33"},
},
{
para402{"112", 1},
ans402{"11"},
},
{
para402{"1432219", 3},
ans402{"1219"},
},
{
para402{"10200", 1},
ans402{"200"},
},
{
para402{"10", 2},
ans402{"0"},
},
{
para402{"19", 2},
ans402{"0"},
},
}
fmt.Printf("------------------------Leetcode Problem 402------------------------\n")
for _, q := range qs {
_, p := q.ans402, q.para402
fmt.Printf("【input】:%v 【output】:%v\n", p, removeKdigits(p.num, p.k))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0402.Remove-K-Digits/402. Remove K Digits.go | leetcode/0402.Remove-K-Digits/402. Remove K Digits.go | package leetcode
func removeKdigits(num string, k int) string {
if k == len(num) {
return "0"
}
res := []byte{}
for i := 0; i < len(num); i++ {
c := num[i]
for k > 0 && len(res) > 0 && c < res[len(res)-1] {
res = res[:len(res)-1]
k--
}
res = append(res, c)
}
res = res[:len(res)-k]
// trim leading zeros
for len(res) > 1 && res[0] == '0' {
res = res[1:]
}
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/0703.Kth-Largest-Element-in-a-Stream/703. Kth Largest Element in a Stream.go | leetcode/0703.Kth-Largest-Element-in-a-Stream/703. Kth Largest Element in a Stream.go | package leetcode
import (
"container/heap"
"sort"
)
type KthLargest struct {
sort.IntSlice
k int
}
func Constructor(k int, nums []int) KthLargest {
kl := KthLargest{k: k}
for _, val := range nums {
kl.Add(val)
}
return kl
}
func (kl *KthLargest) Push(v interface{}) {
kl.IntSlice = append(kl.IntSlice, v.(int))
}
func (kl *KthLargest) Pop() interface{} {
a := kl.IntSlice
v := a[len(a)-1]
kl.IntSlice = a[:len(a)-1]
return v
}
func (kl *KthLargest) Add(val int) int {
heap.Push(kl, val)
if kl.Len() > kl.k {
heap.Pop(kl)
}
return kl.IntSlice[0]
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0703.Kth-Largest-Element-in-a-Stream/703. Kth Largest Element in a Stream_test.go | leetcode/0703.Kth-Largest-Element-in-a-Stream/703. Kth Largest Element in a Stream_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem703(t *testing.T) {
obj := Constructor(3, []int{4, 5, 8, 2})
fmt.Printf("Add 7 = %v\n", obj.Add(3))
fmt.Printf("Add 7 = %v\n", obj.Add(5))
fmt.Printf("Add 7 = %v\n", obj.Add(10))
fmt.Printf("Add 7 = %v\n", obj.Add(9))
fmt.Printf("Add 7 = %v\n", obj.Add(4))
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1010.Pairs-of-Songs-With-Total-Durations-Divisible-by-60/1010. Pairs of Songs With Total Durations Divisible by 60.go | leetcode/1010.Pairs-of-Songs-With-Total-Durations-Divisible-by-60/1010. Pairs of Songs With Total Durations Divisible by 60.go | package leetcode
func numPairsDivisibleBy60(time []int) int {
counts := make([]int, 60)
for _, v := range time {
v %= 60
counts[v]++
}
res := 0
for i := 1; i < len(counts)/2; i++ {
res += counts[i] * counts[60-i]
}
res += (counts[0] * (counts[0] - 1)) / 2
res += (counts[30] * (counts[30] - 1)) / 2
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1010.Pairs-of-Songs-With-Total-Durations-Divisible-by-60/1010. Pairs of Songs With Total Durations Divisible by 60_test.go | leetcode/1010.Pairs-of-Songs-With-Total-Durations-Divisible-by-60/1010. Pairs of Songs With Total Durations Divisible by 60_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1010 struct {
para1010
ans1010
}
// para 是参数
// one 代表第一个参数
type para1010 struct {
time []int
}
// ans 是答案
// one 代表第一个答案
type ans1010 struct {
one int
}
func Test_Problem1010(t *testing.T) {
qs := []question1010{
{
para1010{[]int{30, 20, 150, 100, 40}},
ans1010{3},
},
{
para1010{[]int{60, 60, 60}},
ans1010{3},
},
}
fmt.Printf("------------------------Leetcode Problem 1010------------------------\n")
for _, q := range qs {
_, p := q.ans1010, q.para1010
fmt.Printf("【input】:%v 【output】:%v\n", p, numPairsDivisibleBy60(p.time))
}
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/1679.Max-Number-of-K-Sum-Pairs/1679. Max Number of K-Sum Pairs_test.go | leetcode/1679.Max-Number-of-K-Sum-Pairs/1679. Max Number of K-Sum Pairs_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1679 struct {
para1679
ans1679
}
// para 是参数
// one 代表第一个参数
type para1679 struct {
nums []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans1679 struct {
one int
}
func Test_Problem1679(t *testing.T) {
qs := []question1679{
{
para1679{[]int{1, 2, 3, 4}, 5},
ans1679{2},
},
{
para1679{[]int{3, 1, 3, 4, 3}, 6},
ans1679{1},
},
{
para1679{[]int{2, 5, 4, 4, 1, 3, 4, 4, 1, 4, 4, 1, 2, 1, 2, 2, 3, 2, 4, 2}, 3},
ans1679{4},
},
{
para1679{[]int{2, 5, 5, 5, 1, 3, 4, 4, 1, 4, 4, 1, 3, 1, 3, 1, 3, 2, 4, 2}, 6},
ans1679{8},
},
}
fmt.Printf("------------------------Leetcode Problem 1679------------------------\n")
for _, q := range qs {
_, p := q.ans1679, q.para1679
fmt.Printf("【input】:%v 【output】:%v\n", p, maxOperations(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/1679.Max-Number-of-K-Sum-Pairs/1679. Max Number of K-Sum Pairs.go | leetcode/1679.Max-Number-of-K-Sum-Pairs/1679. Max Number of K-Sum Pairs.go | package leetcode
// 解法一 优化版
func maxOperations(nums []int, k int) int {
counter, res := make(map[int]int), 0
for _, n := range nums {
counter[n]++
}
if (k & 1) == 0 {
res += counter[k>>1] >> 1
// 能够由 2 个相同的数构成 k 的组合已经都排除出去了,剩下的一个单独的也不能组成 k 了
// 所以这里要把它的频次置为 0 。如果这里不置为 0,下面代码判断逻辑还需要考虑重复使用数字的情况
counter[k>>1] = 0
}
for num, freq := range counter {
if num <= k/2 {
remain := k - num
if counter[remain] < freq {
res += counter[remain]
} else {
res += freq
}
}
}
return res
}
// 解法二
func maxOperations_(nums []int, k int) int {
counter, res := make(map[int]int), 0
for _, num := range nums {
counter[num]++
remain := k - num
if num == remain {
if counter[num] >= 2 {
res++
counter[num] -= 2
}
} else {
if counter[remain] > 0 {
res++
counter[remain]--
counter[num]--
}
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1235.Maximum-Profit-in-Job-Scheduling/1235. Maximum Profit in Job Scheduling.go | leetcode/1235.Maximum-Profit-in-Job-Scheduling/1235. Maximum Profit in Job Scheduling.go | package leetcode
import "sort"
type job struct {
startTime int
endTime int
profit int
}
func jobScheduling(startTime []int, endTime []int, profit []int) int {
jobs, dp := []job{}, make([]int, len(startTime))
for i := 0; i < len(startTime); i++ {
jobs = append(jobs, job{startTime: startTime[i], endTime: endTime[i], profit: profit[i]})
}
sort.Sort(sortJobs(jobs))
dp[0] = jobs[0].profit
for i := 1; i < len(jobs); i++ {
low, high := 0, i-1
for low < high {
mid := low + (high-low)>>1
if jobs[mid+1].endTime <= jobs[i].startTime {
low = mid + 1
} else {
high = mid
}
}
if jobs[low].endTime <= jobs[i].startTime {
dp[i] = max(dp[i-1], dp[low]+jobs[i].profit)
} else {
dp[i] = max(dp[i-1], jobs[i].profit)
}
}
return dp[len(startTime)-1]
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
type sortJobs []job
func (s sortJobs) Len() int {
return len(s)
}
func (s sortJobs) Less(i, j int) bool {
if s[i].endTime == s[j].endTime {
return s[i].profit < s[j].profit
}
return s[i].endTime < s[j].endTime
}
func (s sortJobs) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1235.Maximum-Profit-in-Job-Scheduling/1235. Maximum Profit in Job Scheduling_test.go | leetcode/1235.Maximum-Profit-in-Job-Scheduling/1235. Maximum Profit in Job Scheduling_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1235 struct {
para1235
ans1235
}
// para 是参数
// one 代表第一个参数
type para1235 struct {
startTime []int
endTime []int
profit []int
}
// ans 是答案
// one 代表第一个答案
type ans1235 struct {
one int
}
func Test_Problem1235(t *testing.T) {
qs := []question1235{
{
para1235{[]int{1, 2, 3, 3}, []int{3, 4, 5, 6}, []int{50, 10, 40, 70}},
ans1235{120},
},
{
para1235{[]int{1, 2, 3, 4, 6}, []int{3, 5, 10, 6, 9}, []int{20, 20, 100, 70, 60}},
ans1235{150},
},
{
para1235{[]int{1, 1, 1}, []int{2, 3, 4}, []int{5, 6, 4}},
ans1235{6},
},
}
fmt.Printf("------------------------Leetcode Problem 1235------------------------\n")
for _, q := range qs {
_, p := q.ans1235, q.para1235
fmt.Printf("【input】:%v 【output】:%v\n", p, jobScheduling(p.startTime, p.endTime, p.profit))
}
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/0232.Implement-Queue-using-Stacks/232. Implement Queue using Stacks_test.go | leetcode/0232.Implement-Queue-using-Stacks/232. Implement Queue using Stacks_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem232(t *testing.T) {
obj := Constructor232()
fmt.Printf("obj = %v\n", obj)
obj.Push(2)
fmt.Printf("obj = %v\n", obj)
obj.Push(10)
fmt.Printf("obj = %v\n", obj)
param2 := obj.Pop()
fmt.Printf("param_2 = %v\n", param2)
param3 := obj.Peek()
fmt.Printf("param_3 = %v\n", param3)
param4 := obj.Empty()
fmt.Printf("param_4 = %v\n", param4)
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0232.Implement-Queue-using-Stacks/232. Implement Queue using Stacks.go | leetcode/0232.Implement-Queue-using-Stacks/232. Implement Queue using Stacks.go | package leetcode
type MyQueue struct {
Stack *[]int
Queue *[]int
}
/** Initialize your data structure here. */
func Constructor232() MyQueue {
tmp1, tmp2 := []int{}, []int{}
return MyQueue{Stack: &tmp1, Queue: &tmp2}
}
/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int) {
*this.Stack = append(*this.Stack, x)
}
/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
if len(*this.Queue) == 0 {
this.fromStackToQueue(this.Stack, this.Queue)
}
popped := (*this.Queue)[len(*this.Queue)-1]
*this.Queue = (*this.Queue)[:len(*this.Queue)-1]
return popped
}
/** Get the front element. */
func (this *MyQueue) Peek() int {
if len(*this.Queue) == 0 {
this.fromStackToQueue(this.Stack, this.Queue)
}
return (*this.Queue)[len(*this.Queue)-1]
}
/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
return len(*this.Stack)+len(*this.Queue) == 0
}
func (this *MyQueue) fromStackToQueue(s, q *[]int) {
for len(*s) > 0 {
popped := (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
*q = append(*q, popped)
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0864.Shortest-Path-to-Get-All-Keys/864. Shortest Path to Get All Keys.go | leetcode/0864.Shortest-Path-to-Get-All-Keys/864. Shortest Path to Get All Keys.go | package leetcode
import (
"math"
"strings"
)
var dir = [][]int{
{-1, 0},
{0, 1},
{1, 0},
{0, -1},
}
// 解法一 BFS,利用状态压缩来过滤筛选状态
func shortestPathAllKeys(grid []string) int {
if len(grid) == 0 {
return 0
}
board, visited, startx, starty, res, fullKeys := make([][]byte, len(grid)), make([][][]bool, len(grid)), 0, 0, 0, 0
for i := 0; i < len(grid); i++ {
board[i] = make([]byte, len(grid[0]))
}
for i, g := range grid {
board[i] = []byte(g)
for _, v := range g {
if v == 'a' || v == 'b' || v == 'c' || v == 'd' || v == 'e' || v == 'f' {
fullKeys |= (1 << uint(v-'a'))
}
}
if strings.Contains(g, "@") {
startx, starty = i, strings.Index(g, "@")
}
}
for i := 0; i < len(visited); i++ {
visited[i] = make([][]bool, len(board[0]))
}
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[0]); j++ {
visited[i][j] = make([]bool, 64)
}
}
queue := []int{}
queue = append(queue, (starty<<16)|(startx<<8))
visited[startx][starty][0] = true
for len(queue) != 0 {
qLen := len(queue)
for i := 0; i < qLen; i++ {
state := queue[0]
queue = queue[1:]
starty, startx = state>>16, (state>>8)&0xFF
keys := state & 0xFF
if keys == fullKeys {
return res
}
for i := 0; i < 4; i++ {
newState := keys
nx := startx + dir[i][0]
ny := starty + dir[i][1]
if !isInBoard(board, nx, ny) {
continue
}
if board[nx][ny] == '#' {
continue
}
flag, canThroughLock := keys&(1<<(board[nx][ny]-'A')), false
if flag != 0 {
canThroughLock = true
}
if isLock(board, nx, ny) && !canThroughLock {
continue
}
if isKey(board, nx, ny) {
newState |= (1 << (board[nx][ny] - 'a'))
}
if visited[nx][ny][newState] {
continue
}
queue = append(queue, (ny<<16)|(nx<<8)|newState)
visited[nx][ny][newState] = true
}
}
res++
}
return -1
}
func isInBoard(board [][]byte, x, y int) bool {
return x >= 0 && x < len(board) && y >= 0 && y < len(board[0])
}
// 解法二 DFS,但是超时了,剪枝条件不够强
func shortestPathAllKeys1(grid []string) int {
if len(grid) == 0 {
return 0
}
board, visited, startx, starty, res, fullKeys := make([][]byte, len(grid)), make([][][]bool, len(grid)), 0, 0, math.MaxInt64, 0
for i := 0; i < len(grid); i++ {
board[i] = make([]byte, len(grid[0]))
}
for i, g := range grid {
board[i] = []byte(g)
for _, v := range g {
if v == 'a' || v == 'b' || v == 'c' || v == 'd' || v == 'e' || v == 'f' {
fullKeys |= (1 << uint(v-'a'))
}
}
if strings.Contains(g, "@") {
startx, starty = i, strings.Index(g, "@")
}
}
for i := 0; i < len(visited); i++ {
visited[i] = make([][]bool, len(board[0]))
}
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[0]); j++ {
visited[i][j] = make([]bool, 64)
}
}
searchKeys(board, &visited, fullKeys, 0, (starty<<16)|(startx<<8), &res, []int{})
if res == math.MaxInt64 {
return -1
}
return res - 1
}
func searchKeys(board [][]byte, visited *[][][]bool, fullKeys, step, state int, res *int, path []int) {
y, x := state>>16, (state>>8)&0xFF
keys := state & 0xFF
if keys == fullKeys {
*res = min(*res, step)
return
}
flag, canThroughLock := keys&(1<<(board[x][y]-'A')), false
if flag != 0 {
canThroughLock = true
}
newState := keys
//fmt.Printf("x = %v y = %v fullKeys = %v keys = %v step = %v res = %v path = %v state = %v\n", x, y, fullKeys, keys, step, *res, path, state)
if (board[x][y] != '#' && !isLock(board, x, y)) || (isLock(board, x, y) && canThroughLock) {
if isKey(board, x, y) {
newState |= (1 << uint(board[x][y]-'a'))
}
(*visited)[x][y][newState] = true
path = append(path, x)
path = append(path, y)
for i := 0; i < 4; i++ {
nx := x + dir[i][0]
ny := y + dir[i][1]
if isInBoard(board, nx, ny) && !(*visited)[nx][ny][newState] {
searchKeys(board, visited, fullKeys, step+1, (ny<<16)|(nx<<8)|newState, res, path)
}
}
(*visited)[x][y][keys] = false
path = path[:len(path)-1]
path = path[:len(path)-1]
}
}
func isLock(board [][]byte, x, y int) bool {
if (board[x][y] == 'A') || (board[x][y] == 'B') ||
(board[x][y] == 'C') || (board[x][y] == 'D') ||
(board[x][y] == 'E') || (board[x][y] == 'F') {
return true
}
return false
}
func isKey(board [][]byte, x, y int) bool {
if (board[x][y] == 'a') || (board[x][y] == 'b') ||
(board[x][y] == 'c') || (board[x][y] == 'd') ||
(board[x][y] == 'e') || (board[x][y] == 'f') {
return true
}
return false
}
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/0864.Shortest-Path-to-Get-All-Keys/864. Shortest Path to Get All Keys_test.go | leetcode/0864.Shortest-Path-to-Get-All-Keys/864. Shortest Path to Get All Keys_test.go | package leetcode
import (
"fmt"
"testing"
)
type question864 struct {
para864
ans864
}
// para 是参数
// one 代表第一个参数
type para864 struct {
one []string
}
// ans 是答案
// one 代表第一个答案
type ans864 struct {
one int
}
func Test_Problem864(t *testing.T) {
qs := []question864{
{
para864{[]string{".##..##..B", "##...#...#", "..##..#...", ".#..#b...#", "#.##.a.###", ".#....#...", ".##..#.#..", ".....###@.", "..........", ".........A"}},
ans864{11},
},
{
para864{[]string{"Dd#b@", ".fE.e", "##.B.", "#.cA.", "aF.#C"}},
ans864{14},
},
{
para864{[]string{"@...a", ".###A", "b.BCc"}},
ans864{10},
},
{
para864{[]string{"@Aa"}},
ans864{-1},
},
{
para864{[]string{"b", "A", "a", "@", "B"}},
ans864{3},
},
{
para864{[]string{"@.a.#", "#####", "b.A.B"}},
ans864{-1},
},
{
para864{[]string{"@.a.#", "###.#", "b.A.B"}},
ans864{8},
},
{
para864{[]string{"@..aA", "..B#.", "....b"}},
ans864{6},
},
}
fmt.Printf("------------------------Leetcode Problem 864------------------------\n")
for _, q := range qs {
_, p := q.ans864, q.para864
fmt.Printf("【input】:%v 【output】:%v\n", p, shortestPathAllKeys(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/0705.Design-HashSet/705. Design HashSet.go | leetcode/0705.Design-HashSet/705. Design HashSet.go | package leetcode
type MyHashSet struct {
data []bool
}
/** Initialize your data structure here. */
func Constructor705() MyHashSet {
return MyHashSet{
data: make([]bool, 1000001),
}
}
func (this *MyHashSet) Add(key int) {
this.data[key] = true
}
func (this *MyHashSet) Remove(key int) {
this.data[key] = false
}
/** Returns true if this set contains the specified element */
func (this *MyHashSet) Contains(key int) bool {
return this.data[key]
}
/**
* Your MyHashSet object will be instantiated and called as such:
* obj := Constructor();
* obj.Add(key);
* obj.Remove(key);
* param_3 := obj.Contains(key);
*/
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0705.Design-HashSet/705. Design HashSet_test.go | leetcode/0705.Design-HashSet/705. Design HashSet_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem705(t *testing.T) {
obj := Constructor705()
obj.Add(7)
fmt.Printf("Contains 7 = %v\n", obj.Contains(7))
obj.Remove(10)
fmt.Printf("Contains 10 = %v\n", obj.Contains(10))
obj.Add(20)
fmt.Printf("Contains 20 = %v\n", obj.Contains(20))
obj.Remove(30)
fmt.Printf("Contains 30 = %v\n", obj.Contains(30))
obj.Add(8)
fmt.Printf("Contains 8 = %v\n", obj.Contains(8))
obj.Remove(8)
fmt.Printf("Contains 8 = %v\n", obj.Contains(8))
param1 := obj.Contains(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/0035.Search-Insert-Position/35. Search Insert Position.go | leetcode/0035.Search-Insert-Position/35. Search Insert Position.go | package leetcode
func searchInsert(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + (high-low)>>1
if nums[mid] >= target {
high = mid - 1
} else {
if (mid == len(nums)-1) || (nums[mid+1] >= target) {
return mid + 1
}
low = mid + 1
}
}
return 0
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0035.Search-Insert-Position/35. Search Insert Position_test.go | leetcode/0035.Search-Insert-Position/35. Search Insert Position_test.go | package leetcode
import (
"fmt"
"testing"
)
type question35 struct {
para35
ans35
}
// para 是参数
// one 代表第一个参数
type para35 struct {
nums []int
target int
}
// ans 是答案
// one 代表第一个答案
type ans35 struct {
one int
}
func Test_Problem35(t *testing.T) {
qs := []question35{
{
para35{[]int{1, 3, 5, 6}, 5},
ans35{2},
},
{
para35{[]int{1, 3, 5, 6}, 2},
ans35{1},
},
{
para35{[]int{1, 3, 5, 6}, 7},
ans35{4},
},
{
para35{[]int{1, 3, 5, 6}, 0},
ans35{0},
},
}
fmt.Printf("------------------------Leetcode Problem 35------------------------\n")
for _, q := range qs {
_, p := q.ans35, q.para35
fmt.Printf("【input】:%v 【output】:%v\n", p, searchInsert(p.nums, p.target))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1629.Slowest-Key/1629. Slowest Key.go | leetcode/1629.Slowest-Key/1629. Slowest Key.go | package leetcode
func slowestKey(releaseTimes []int, keysPressed string) byte {
longestDuration, key := releaseTimes[0], keysPressed[0]
for i := 1; i < len(releaseTimes); i++ {
duration := releaseTimes[i] - releaseTimes[i-1]
if duration > longestDuration {
longestDuration = duration
key = keysPressed[i]
} else if duration == longestDuration && keysPressed[i] > key {
key = keysPressed[i]
}
}
return key
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1629.Slowest-Key/1629. Slowest Key_test.go | leetcode/1629.Slowest-Key/1629. Slowest Key_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1629 struct {
para1629
ans1629
}
// para 是参数
// one 代表第一个参数
type para1629 struct {
releaseTimes []int
keysPressed string
}
// ans 是答案
// one 代表第一个答案
type ans1629 struct {
one byte
}
func Test_Problem1629(t *testing.T) {
qs := []question1629{
{
para1629{[]int{9, 29, 49, 50}, "cbcd"},
ans1629{'c'},
},
{
para1629{[]int{12, 23, 36, 46, 62}, "spuda"},
ans1629{'a'},
},
}
fmt.Printf("------------------------Leetcode Problem 1629------------------------\n")
for _, q := range qs {
_, p := q.ans1629, q.para1629
fmt.Printf("【input】:%v 【output】:%c \n", p, slowestKey(p.releaseTimes, p.keysPressed))
}
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/0707.Design-Linked-List/707. Design Linked List_test.go | leetcode/0707.Design-Linked-List/707. Design Linked List_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem707(t *testing.T) {
obj := Constructor()
fmt.Printf("obj = %v\n", MList2Ints(&obj))
param1 := obj.Get(1)
fmt.Printf("param_1 = %v obj = %v\n", param1, MList2Ints(&obj))
obj.AddAtHead(38)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.AddAtHead(45)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.DeleteAtIndex(2)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.AddAtIndex(1, 24)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.AddAtTail(36)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.AddAtIndex(3, 72)
obj.AddAtTail(76)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.AddAtHead(7)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.AddAtHead(36)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.AddAtHead(34)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
obj.AddAtTail(91)
fmt.Printf("obj = %v\n", MList2Ints(&obj))
fmt.Printf("\n\n\n")
obj1 := Constructor()
fmt.Printf("obj1 = %v\n", MList2Ints(&obj1))
param2 := obj1.Get(0)
fmt.Printf("param_2 = %v obj1 = %v\n", param2, MList2Ints(&obj1))
obj1.AddAtIndex(1, 2)
fmt.Printf("obj1 = %v\n", MList2Ints(&obj1))
param2 = obj1.Get(0)
fmt.Printf("param_2 = %v obj1 = %v\n", param2, MList2Ints(&obj1))
param2 = obj1.Get(1)
fmt.Printf("param_2 = %v obj1 = %v\n", param2, MList2Ints(&obj1))
obj1.AddAtIndex(0, 1)
fmt.Printf("obj1 = %v\n", MList2Ints(&obj1))
param2 = obj1.Get(0)
fmt.Printf("param_1 = %v obj1 = %v\n", param2, MList2Ints(&obj1))
param2 = obj1.Get(1)
fmt.Printf("param_2 = %v obj1 = %v\n", param2, MList2Ints(&obj1))
}
func MList2Ints(head *MyLinkedList) []int {
res := []int{}
cur := head.head
for cur != nil {
res = append(res, cur.Val)
cur = cur.Next
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0707.Design-Linked-List/707. Design Linked List.go | leetcode/0707.Design-Linked-List/707. Design Linked List.go | package leetcode
type MyLinkedList struct {
head *Node
}
type Node struct {
Val int
Next *Node
Prev *Node
}
/** Initialize your data structure here. */
func Constructor() MyLinkedList {
return MyLinkedList{}
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
func (this *MyLinkedList) Get(index int) int {
curr := this.head
for i := 0; i < index && curr != nil; i++ {
curr = curr.Next
}
if curr != nil {
return curr.Val
} else {
return -1
}
}
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
func (this *MyLinkedList) AddAtHead(val int) {
node := &Node{Val: val}
node.Next = this.head
if this.head != nil {
this.head.Prev = node
}
this.head = node
}
/** Append a node of value val to the last element of the linked list. */
func (this *MyLinkedList) AddAtTail(val int) {
if this.head == nil {
this.AddAtHead(val)
return
}
node := &Node{Val: val}
curr := this.head
for curr != nil && curr.Next != nil {
curr = curr.Next
}
node.Prev = curr
curr.Next = node
}
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
func (this *MyLinkedList) AddAtIndex(index int, val int) {
if index == 0 {
this.AddAtHead(val)
} else {
node := &Node{Val: val}
curr := this.head
for i := 0; i < index-1 && curr != nil; i++ {
curr = curr.Next
}
if curr != nil {
node.Next = curr.Next
node.Prev = curr
if node.Next != nil {
node.Next.Prev = node
}
curr.Next = node
}
}
}
/** Delete the index-th node in the linked list, if the index is valid. */
func (this *MyLinkedList) DeleteAtIndex(index int) {
if index == 0 {
this.head = this.head.Next
if this.head != nil {
this.head.Prev = nil
}
} else {
curr := this.head
for i := 0; i < index-1 && curr != nil; i++ {
curr = curr.Next
}
if curr != nil && curr.Next != nil {
curr.Next = curr.Next.Next
if curr.Next != nil {
curr.Next.Prev = curr
}
}
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* obj := Constructor();
* param_1 := obj.Get(index);
* obj.AddAtHead(val);
* obj.AddAtTail(val);
* obj.AddAtIndex(index,val);
* obj.DeleteAtIndex(index);
*/
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0342.Power-of-Four/342. Power of Four_test.go | leetcode/0342.Power-of-Four/342. Power of Four_test.go | package leetcode
import (
"fmt"
"testing"
)
type question342 struct {
para342
ans342
}
// para 是参数
// one 代表第一个参数
type para342 struct {
one int
}
// ans 是答案
// one 代表第一个答案
type ans342 struct {
one bool
}
func Test_Problem342(t *testing.T) {
qs := []question342{
{
para342{16},
ans342{true},
},
{
para342{5},
ans342{false},
},
}
fmt.Printf("------------------------Leetcode Problem 342------------------------\n")
for _, q := range qs {
_, p := q.ans342, q.para342
fmt.Printf("【input】:%v 【output】:%v\n", p, isPowerOfFour(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/0342.Power-of-Four/342. Power of Four.go | leetcode/0342.Power-of-Four/342. Power of Four.go | package leetcode
// 解法一 数论
func isPowerOfFour(num int) bool {
return num > 0 && (num&(num-1)) == 0 && (num-1)%3 == 0
}
// 解法二 循环
func isPowerOfFour1(num int) bool {
for num >= 4 {
if num%4 == 0 {
num = num / 4
} else {
return false
}
}
return num == 1
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0080.Remove-Duplicates-from-Sorted-Array-II/80. Remove Duplicates from Sorted Array II_test.go | leetcode/0080.Remove-Duplicates-from-Sorted-Array-II/80. Remove Duplicates from Sorted Array II_test.go | package leetcode
import (
"fmt"
"testing"
)
type question80 struct {
para80
ans80
}
// para 是参数
// one 代表第一个参数
type para80 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans80 struct {
one int
}
func Test_Problem80(t *testing.T) {
qs := []question80{
{
para80{[]int{1, 1, 2}},
ans80{3},
},
{
para80{[]int{0, 0, 1, 1, 1, 1, 2, 3, 4, 4}},
ans80{8},
},
{
para80{[]int{0, 0, 0, 0, 0}},
ans80{2},
},
{
para80{[]int{1}},
ans80{1},
},
{
para80{[]int{0, 0, 1, 1, 1, 1, 2, 3, 3}},
ans80{7},
},
{
para80{[]int{1, 1, 1, 1, 2, 2, 3}},
ans80{5},
},
}
fmt.Printf("------------------------Leetcode Problem 80------------------------\n")
for _, q := range qs {
_, p := q.ans80, q.para80
fmt.Printf("【input】:%v 【output】:%v\n", p.one, removeDuplicates(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/0080.Remove-Duplicates-from-Sorted-Array-II/80. Remove Duplicates from Sorted Array II.go | leetcode/0080.Remove-Duplicates-from-Sorted-Array-II/80. Remove Duplicates from Sorted Array II.go | package leetcode
func removeDuplicates(nums []int) int {
slow := 0
for fast, v := range nums {
if fast < 2 || nums[slow-2] != v {
nums[slow] = v
slow++
}
}
return slow
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0153.Find-Minimum-in-Rotated-Sorted-Array/153. Find Minimum in Rotated Sorted Array_test.go | leetcode/0153.Find-Minimum-in-Rotated-Sorted-Array/153. Find Minimum in Rotated Sorted Array_test.go | package leetcode
import (
"fmt"
"testing"
)
type question153 struct {
para153
ans153
}
// para 是参数
// one 代表第一个参数
type para153 struct {
nums []int
}
// ans 是答案
// one 代表第一个答案
type ans153 struct {
one int
}
func Test_Problem153(t *testing.T) {
qs := []question153{
{
para153{[]int{5, 1, 2, 3, 4}},
ans153{1},
},
{
para153{[]int{1}},
ans153{1},
},
{
para153{[]int{1, 2}},
ans153{1},
},
{
para153{[]int{2, 1}},
ans153{1},
},
{
para153{[]int{2, 3, 1}},
ans153{1},
},
{
para153{[]int{1, 2, 3}},
ans153{1},
},
{
para153{[]int{3, 4, 5, 1, 2}},
ans153{1},
},
{
para153{[]int{4, 5, 6, 7, 0, 1, 2}},
ans153{0},
},
}
fmt.Printf("------------------------Leetcode Problem 153------------------------\n")
for _, q := range qs {
_, p := q.ans153, q.para153
fmt.Printf("【input】:%v 【output】:%v\n", p, findMin(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/0153.Find-Minimum-in-Rotated-Sorted-Array/153. Find Minimum in Rotated Sorted Array.go | leetcode/0153.Find-Minimum-in-Rotated-Sorted-Array/153. Find Minimum in Rotated Sorted Array.go | package leetcode
// 解法一 二分
func findMin(nums []int) int {
low, high := 0, len(nums)-1
for low < high {
if nums[low] < nums[high] {
return nums[low]
}
mid := low + (high-low)>>1
if nums[mid] >= nums[low] {
low = mid + 1
} else {
high = mid
}
}
return nums[low]
}
// 解法二 二分
func findMin1(nums []int) int {
if len(nums) == 0 {
return 0
}
if len(nums) == 1 {
return nums[0]
}
if nums[len(nums)-1] > nums[0] {
return nums[0]
}
low, high := 0, len(nums)-1
for low <= high {
mid := low + (high-low)>>1
if nums[low] < nums[high] {
return nums[low]
}
if (mid == len(nums)-1 && nums[mid-1] > nums[mid]) || (mid < len(nums)-1 && mid > 0 && nums[mid-1] > nums[mid] && nums[mid] < nums[mid+1]) {
return nums[mid]
}
if nums[mid] > nums[low] && nums[low] > nums[high] { // mid 在数值大的一部分区间里
low = mid + 1
} else if nums[mid] < nums[low] && nums[low] > nums[high] { // mid 在数值小的一部分区间里
high = mid - 1
} else {
if nums[low] == nums[mid] {
low++
}
if nums[high] == nums[mid] {
high--
}
}
}
return -1
}
// 解法三 暴力
func findMin2(nums []int) int {
min := nums[0]
for _, num := range nums[1:] {
if min > num {
min = num
}
}
return min
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0242.Valid-Anagram/242. Valid Anagram_test.go | leetcode/0242.Valid-Anagram/242. Valid Anagram_test.go | package leetcode
import (
"fmt"
"testing"
)
type question242 struct {
para242
ans242
}
// para 是参数
// one 代表第一个参数
type para242 struct {
one string
two string
}
// ans 是答案
// one 代表第一个答案
type ans242 struct {
one bool
}
func Test_Problem242(t *testing.T) {
qs := []question242{
{
para242{"", ""},
ans242{true},
},
{
para242{"", "1"},
ans242{false},
},
{
para242{"anagram", "nagaram"},
ans242{true},
},
{
para242{"rat", "car"},
ans242{false},
},
{
para242{"a", "ab"},
ans242{false},
},
{
para242{"ab", "a"},
ans242{false},
},
{
para242{"aa", "bb"},
ans242{false},
},
}
fmt.Printf("------------------------Leetcode Problem 242------------------------\n")
for _, q := range qs {
_, p := q.ans242, q.para242
fmt.Printf("【input】:%v 【output】:%v\n", p, isAnagram(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/0242.Valid-Anagram/242. Valid Anagram.go | leetcode/0242.Valid-Anagram/242. Valid Anagram.go | package leetcode
// 解法一
func isAnagram(s string, t string) bool {
alphabet := make([]int, 26)
sBytes := []byte(s)
tBytes := []byte(t)
if len(sBytes) != len(tBytes) {
return false
}
for i := 0; i < len(sBytes); i++ {
alphabet[sBytes[i]-'a']++
}
for i := 0; i < len(tBytes); i++ {
alphabet[tBytes[i]-'a']--
}
for i := 0; i < 26; i++ {
if alphabet[i] != 0 {
return false
}
}
return true
}
// 解法二
func isAnagram1(s string, t string) bool {
hash := map[rune]int{}
for _, value := range s {
hash[value]++
}
for _, value := range t {
hash[value]--
}
for _, value := range hash {
if value != 0 {
return false
}
}
return true
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1104.Path-In-Zigzag-Labelled-Binary-Tree/1104.Path In Zigzag Labelled Binary Tree_test.go | leetcode/1104.Path-In-Zigzag-Labelled-Binary-Tree/1104.Path In Zigzag Labelled Binary Tree_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1104 struct {
para1104
ans1104
}
// para 是参数
type para1104 struct {
label int
}
// ans 是答案
type ans1104 struct {
ans []int
}
func Test_Problem1104(t *testing.T) {
qs := []question1104{
{
para1104{14},
ans1104{[]int{1, 3, 4, 14}},
},
{
para1104{26},
ans1104{[]int{1, 2, 6, 10, 26}},
},
}
fmt.Printf("------------------------Leetcode Problem 1104------------------------\n")
for _, q := range qs {
_, p := q.ans1104, q.para1104
fmt.Printf("【input】:%v 【output】:%v \n", p, pathInZigZagTree(p.label))
}
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/1104.Path-In-Zigzag-Labelled-Binary-Tree/1104.Path In Zigzag Labelled Binary Tree.go | leetcode/1104.Path-In-Zigzag-Labelled-Binary-Tree/1104.Path In Zigzag Labelled Binary Tree.go | package leetcode
func pathInZigZagTree(label int) []int {
level := getLevel(label)
ans := []int{label}
curIndex := label - (1 << level)
parent := 0
for level >= 1 {
parent, curIndex = getParent(curIndex, level)
ans = append(ans, parent)
level--
}
ans = reverse(ans)
return ans
}
func getLevel(label int) int {
level := 0
nums := 0
for {
nums += 1 << level
if nums >= label {
return level
}
level++
}
}
func getParent(index int, level int) (parent int, parentIndex int) {
parentIndex = 1<<(level-1) - 1 + (index/2)*(-1)
parent = 1<<(level-1) + parentIndex
return
}
func reverse(nums []int) []int {
left, right := 0, len(nums)-1
for left < right {
nums[left], nums[right] = nums[right], nums[left]
left++
right--
}
return nums
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1480.Running-Sum-of-1d-Array/1480. Running Sum of 1d Array.go | leetcode/1480.Running-Sum-of-1d-Array/1480. Running Sum of 1d Array.go | package leetcode
func runningSum(nums []int) []int {
dp := make([]int, len(nums)+1)
dp[0] = 0
for i := 1; i <= len(nums); i++ {
dp[i] = dp[i-1] + nums[i-1]
}
return dp[1:]
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1480.Running-Sum-of-1d-Array/1480. Running Sum of 1d Array_test.go | leetcode/1480.Running-Sum-of-1d-Array/1480. Running Sum of 1d Array_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1480 struct {
para1480
ans1480
}
// para 是参数
// one 代表第一个参数
type para1480 struct {
nums []int
}
// ans 是答案
// one 代表第一个答案
type ans1480 struct {
one []int
}
func Test_Problem1480(t *testing.T) {
qs := []question1480{
{
para1480{[]int{1, 2, 3, 4}},
ans1480{[]int{1, 3, 6, 10}},
},
{
para1480{[]int{1, 1, 1, 1, 1}},
ans1480{[]int{1, 2, 3, 4, 5}},
},
{
para1480{[]int{3, 1, 2, 10, 1}},
ans1480{[]int{3, 4, 6, 16, 17}},
},
}
fmt.Printf("------------------------Leetcode Problem 1480------------------------\n")
for _, q := range qs {
_, p := q.ans1480, q.para1480
fmt.Printf("【input】:%v 【output】:%v \n", p, runningSum(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/0823.Binary-Trees-With-Factors/823. Binary Trees With Factors_test.go | leetcode/0823.Binary-Trees-With-Factors/823. Binary Trees With Factors_test.go | package leetcode
import (
"fmt"
"testing"
)
type question823 struct {
para823
ans823
}
// para 是参数
// one 代表第一个参数
type para823 struct {
arr []int
}
// ans 是答案
// one 代表第一个答案
type ans823 struct {
one int
}
func Test_Problem823(t *testing.T) {
qs := []question823{
{
para823{[]int{2, 4}},
ans823{3},
},
{
para823{[]int{2, 4, 5, 10}},
ans823{7},
},
}
fmt.Printf("------------------------Leetcode Problem 823------------------------\n")
for _, q := range qs {
_, p := q.ans823, q.para823
fmt.Printf("【input】:%v 【output】:%v\n", p, numFactoredBinaryTrees(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/0823.Binary-Trees-With-Factors/823. Binary Trees With Factors.go | leetcode/0823.Binary-Trees-With-Factors/823. Binary Trees With Factors.go | package leetcode
import (
"sort"
)
const mod = 1e9 + 7
// 解法一 DFS
func numFactoredBinaryTrees(arr []int) int {
sort.Ints(arr)
numDict := map[int]bool{}
for _, num := range arr {
numDict[num] = true
}
dict, res := make(map[int][][2]int), 0
for i, num := range arr {
for j := i; j < len(arr) && num*arr[j] <= arr[len(arr)-1]; j++ {
tmp := num * arr[j]
if !numDict[tmp] {
continue
}
dict[tmp] = append(dict[tmp], [2]int{num, arr[j]})
}
}
cache := make(map[int]int)
for _, num := range arr {
res = (res + dfs(num, dict, cache)) % mod
}
return res
}
func dfs(num int, dict map[int][][2]int, cache map[int]int) int {
if val, ok := cache[num]; ok {
return val
}
res := 1
for _, tuple := range dict[num] {
a, b := tuple[0], tuple[1]
x, y := dfs(a, dict, cache), dfs(b, dict, cache)
tmp := x * y
if a != b {
tmp *= 2
}
res = (res + tmp) % mod
}
cache[num] = res
return res
}
// 解法二 DP
func numFactoredBinaryTrees1(arr []int) int {
dp := make(map[int]int)
sort.Ints(arr)
for i, curNum := range arr {
for j := 0; j < i; j++ {
factor := arr[j]
quotient, remainder := curNum/factor, curNum%factor
if remainder == 0 {
dp[curNum] += dp[factor] * dp[quotient]
}
}
dp[curNum]++
}
totalCount := 0
for _, count := range dp {
totalCount += count
}
return totalCount % mod
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0147.Insertion-Sort-List/147. Insertion Sort List.go | leetcode/0147.Insertion-Sort-List/147. Insertion Sort 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 insertionSortList(head *ListNode) *ListNode {
if head == nil {
return head
}
newHead := &ListNode{Val: 0, Next: nil} // 这里初始化不要直接指向 head,为了下面循环可以统一处理
cur, pre := head, newHead
for cur != nil {
next := cur.Next
for pre.Next != nil && pre.Next.Val < cur.Val {
pre = pre.Next
}
cur.Next = pre.Next
pre.Next = cur
pre = newHead // 归位,重头开始
cur = next
}
return newHead.Next
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0147.Insertion-Sort-List/147. Insertion Sort List_test.go | leetcode/0147.Insertion-Sort-List/147. Insertion Sort List_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question147 struct {
para147
ans147
}
// para 是参数
// one 代表第一个参数
type para147 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans147 struct {
one []int
}
func Test_Problem147(t *testing.T) {
qs := []question147{
{
para147{[]int{4, 2, 1, 3}},
ans147{[]int{1, 2, 3, 4}},
},
{
para147{[]int{1}},
ans147{[]int{1}},
},
{
para147{[]int{-1, 5, 3, 4, 0}},
ans147{[]int{-1, 0, 3, 4, 5}},
},
{
para147{[]int{}},
ans147{[]int{}},
},
}
fmt.Printf("------------------------Leetcode Problem 147------------------------\n")
for _, q := range qs {
_, p := q.ans147, q.para147
fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(insertionSortList(structures.Ints2List(p.one))))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0350.Intersection-of-Two-Arrays-II/350. Intersection of Two Arrays II_test.go | leetcode/0350.Intersection-of-Two-Arrays-II/350. Intersection of Two Arrays II_test.go | package leetcode
import (
"fmt"
"testing"
)
type question350 struct {
para350
ans350
}
// para 是参数
// one 代表第一个参数
type para350 struct {
one []int
another []int
}
// ans 是答案
// one 代表第一个答案
type ans350 struct {
one []int
}
func Test_Problem350(t *testing.T) {
qs := []question350{
{
para350{[]int{}, []int{}},
ans350{[]int{}},
},
{
para350{[]int{1}, []int{1}},
ans350{[]int{1}},
},
{
para350{[]int{1, 2, 3, 4}, []int{1, 2, 3, 4}},
ans350{[]int{1, 2, 3, 4}},
},
{
para350{[]int{1, 2, 2, 1}, []int{2, 2}},
ans350{[]int{2, 2}},
},
{
para350{[]int{1}, []int{9, 9, 9, 9, 9}},
ans350{[]int{}},
},
{
para350{[]int{4, 9, 5}, []int{9, 4, 9, 8, 4}},
ans350{[]int{9, 4}},
},
{
para350{[]int{4, 9, 5, 9, 4}, []int{9, 4, 9, 8, 4, 7, 9, 4, 4, 9}},
ans350{[]int{9, 4, 9, 4}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 350------------------------\n")
for _, q := range qs {
_, p := q.ans350, q.para350
fmt.Printf("【input】:%v 【output】:%v\n", p, intersect(p.one, 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/0350.Intersection-of-Two-Arrays-II/350. Intersection of Two Arrays II.go | leetcode/0350.Intersection-of-Two-Arrays-II/350. Intersection of Two Arrays II.go | package leetcode
func intersect(nums1 []int, nums2 []int) []int {
m := map[int]int{}
var res []int
for _, n := range nums1 {
m[n]++
}
for _, n := range nums2 {
if m[n] > 0 {
res = append(res, n)
m[n]--
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0841.Keys-and-Rooms/841. Keys and Rooms_test.go | leetcode/0841.Keys-and-Rooms/841. Keys and Rooms_test.go | package leetcode
import (
"fmt"
"testing"
)
type question841 struct {
para841
ans841
}
// para 是参数
// one 代表第一个参数
type para841 struct {
rooms [][]int
}
// ans 是答案
// one 代表第一个答案
type ans841 struct {
one bool
}
func Test_Problem841(t *testing.T) {
qs := []question841{
{
para841{[][]int{{1}, {2}, {3}, {}}},
ans841{true},
},
{
para841{[][]int{{1, 3}, {3, 0, 1}, {2}, {0}}},
ans841{false},
},
}
fmt.Printf("------------------------Leetcode Problem 841------------------------\n")
for _, q := range qs {
_, p := q.ans841, q.para841
fmt.Printf("【input】:%v 【output】:%v\n", p, canVisitAllRooms(p.rooms))
}
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/0841.Keys-and-Rooms/841. Keys and Rooms.go | leetcode/0841.Keys-and-Rooms/841. Keys and Rooms.go | package leetcode
func canVisitAllRooms(rooms [][]int) bool {
visited := make(map[int]bool)
visited[0] = true
dfsVisitAllRooms(rooms, visited, 0)
return len(rooms) == len(visited)
}
func dfsVisitAllRooms(es [][]int, visited map[int]bool, from int) {
for _, to := range es[from] {
if visited[to] {
continue
}
visited[to] = true
dfsVisitAllRooms(es, visited, to)
}
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0528.Random-Pick-with-Weight/528. Random Pick with Weight.go | leetcode/0528.Random-Pick-with-Weight/528. Random Pick with Weight.go | package leetcode
import (
"math/rand"
)
// Solution528 define
type Solution528 struct {
prefixSum []int
}
// Constructor528 define
func Constructor528(w []int) Solution528 {
prefixSum := make([]int, len(w))
for i, e := range w {
if i == 0 {
prefixSum[i] = e
continue
}
prefixSum[i] = prefixSum[i-1] + e
}
return Solution528{prefixSum: prefixSum}
}
// PickIndex define
func (so *Solution528) PickIndex() int {
n := rand.Intn(so.prefixSum[len(so.prefixSum)-1]) + 1
low, high := 0, len(so.prefixSum)-1
for low < high {
mid := low + (high-low)>>1
if so.prefixSum[mid] == n {
return mid
} else if so.prefixSum[mid] < n {
low = mid + 1
} else {
high = mid
}
}
return low
}
/**
* Your Solution object will be instantiated and called as such:
* obj := Constructor(w);
* param_1 := obj.PickIndex();
*/
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0528.Random-Pick-with-Weight/528. Random Pick with Weight_test.go | leetcode/0528.Random-Pick-with-Weight/528. Random Pick with Weight_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem528(t *testing.T) {
w := []int{1, 3}
sol := Constructor528(w)
fmt.Printf("1.PickIndex = %v\n", sol.PickIndex())
fmt.Printf("2.PickIndex = %v\n", sol.PickIndex())
fmt.Printf("3.PickIndex = %v\n", sol.PickIndex())
fmt.Printf("4.PickIndex = %v\n", sol.PickIndex())
fmt.Printf("5.PickIndex = %v\n", sol.PickIndex())
fmt.Printf("6.PickIndex = %v\n", sol.PickIndex())
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1260.Shift-2D-Grid/1260. Shift 2D Grid.go | leetcode/1260.Shift-2D-Grid/1260. Shift 2D Grid.go | package leetcode
func shiftGrid(grid [][]int, k int) [][]int {
x, y := len(grid[0]), len(grid)
newGrid := make([][]int, y)
for i := 0; i < y; i++ {
newGrid[i] = make([]int, x)
}
for i := 0; i < y; i++ {
for j := 0; j < x; j++ {
ny := (k / x) + i
if (j + (k % x)) >= x {
ny++
}
newGrid[ny%y][(j+(k%x))%x] = grid[i][j]
}
}
return newGrid
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1260.Shift-2D-Grid/1260. Shift 2D Grid_test.go | leetcode/1260.Shift-2D-Grid/1260. Shift 2D Grid_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1260 struct {
para1260
ans1260
}
// para 是参数
// one 代表第一个参数
type para1260 struct {
grid [][]int
k int
}
// ans 是答案
// one 代表第一个答案
type ans1260 struct {
one [][]int
}
func Test_Problem1260(t *testing.T) {
qs := []question1260{
{
para1260{[][]int{{3, 7, 8}, {9, 11, 13}, {15, 16, 17}}, 2},
ans1260{[][]int{{16, 17, 3}, {7, 8, 9}, {11, 13, 15}}},
},
{
para1260{[][]int{{1, 10, 4, 2}, {9, 3, 8, 7}, {15, 16, 17, 12}}, 10},
ans1260{[][]int{{4, 2, 9, 3}, {8, 7, 15, 16}, {17, 12, 1, 10}}},
},
{
para1260{[][]int{{3, 8, 1, 9}, {19, 7, 2, 5}, {4, 6, 11, 10}, {12, 0, 21, 13}}, 4},
ans1260{[][]int{{12, 0, 21, 13}, {3, 8, 1, 9}, {19, 7, 2, 5}, {4, 6, 11, 10}}},
},
{
para1260{[][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 9},
ans1260{[][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 1260------------------------\n")
for _, q := range qs {
_, p := q.ans1260, q.para1260
fmt.Printf("【input】:%v 【output】:%v\n", p, shiftGrid(p.grid, 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/1763.Longest-Nice-Substring/1763. Longest Nice Substring.go | leetcode/1763.Longest-Nice-Substring/1763. Longest Nice Substring.go | package leetcode
import "unicode"
// 解法一 分治,时间复杂度 O(n)
func longestNiceSubstring(s string) string {
if len(s) < 2 {
return ""
}
chars := map[rune]int{}
for _, r := range s {
chars[r]++
}
for i := 0; i < len(s); i++ {
r := rune(s[i])
_, u := chars[unicode.ToUpper(r)]
_, l := chars[unicode.ToLower(r)]
if u && l {
continue
}
left := longestNiceSubstring(s[:i])
right := longestNiceSubstring(s[i+1:])
if len(left) >= len(right) {
return left
} else {
return right
}
}
return s
}
// 解法二 用二进制表示状态
func longestNiceSubstring1(s string) (ans string) {
for i := range s {
lower, upper := 0, 0
for j := i; j < len(s); j++ {
if unicode.IsLower(rune(s[j])) {
lower |= 1 << (s[j] - 'a')
} else {
upper |= 1 << (s[j] - 'A')
}
if lower == upper && j-i+1 > len(ans) {
ans = s[i : j+1]
}
}
}
return
}
// 解法三 暴力枚举,时间复杂度 O(n^2)
func longestNiceSubstring2(s string) string {
res := ""
for i := 0; i < len(s); i++ {
m := map[byte]int{}
m[s[i]]++
for j := i + 1; j < len(s); j++ {
m[s[j]]++
if checkNiceString(m) && (j-i+1 > len(res)) {
res = s[i : j+1]
}
}
}
return res
}
func checkNiceString(m map[byte]int) bool {
for k := range m {
if k >= 97 && k <= 122 {
if _, ok := m[k-32]; !ok {
return false
}
}
if k >= 65 && k <= 90 {
if _, ok := m[k+32]; !ok {
return false
}
}
}
return true
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1763.Longest-Nice-Substring/1763. Longest Nice Substring_test.go | leetcode/1763.Longest-Nice-Substring/1763. Longest Nice Substring_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1763 struct {
para1763
ans1763
}
// para 是参数
// one 代表第一个参数
type para1763 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans1763 struct {
one string
}
func Test_Problem1763(t *testing.T) {
qs := []question1763{
{
para1763{"YazaAay"},
ans1763{"aAa"},
},
{
para1763{"Bb"},
ans1763{"Bb"},
},
{
para1763{"c"},
ans1763{""},
},
}
fmt.Printf("------------------------Leetcode Problem 1763------------------------\n")
for _, q := range qs {
_, p := q.ans1763, q.para1763
fmt.Printf("【input】:%v 【output】:%v\n", p, longestNiceSubstring(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/0001.Two-Sum/1. Two Sum_test.go | leetcode/0001.Two-Sum/1. Two Sum_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1 struct {
para1
ans1
}
// para 是参数
// one 代表第一个参数
type para1 struct {
nums []int
target int
}
// ans 是答案
// one 代表第一个答案
type ans1 struct {
one []int
}
func Test_Problem1(t *testing.T) {
qs := []question1{
{
para1{[]int{3, 2, 4}, 6},
ans1{[]int{1, 2}},
},
{
para1{[]int{3, 2, 4}, 5},
ans1{[]int{0, 1}},
},
{
para1{[]int{0, 8, 7, 3, 3, 4, 2}, 11},
ans1{[]int{1, 3}},
},
{
para1{[]int{0, 1}, 1},
ans1{[]int{0, 1}},
},
{
para1{[]int{0, 3}, 5},
ans1{[]int{}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 1------------------------\n")
for _, q := range qs {
_, p := q.ans1, q.para1
fmt.Printf("【input】:%v 【output】:%v\n", p, twoSum(p.nums, p.target))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0001.Two-Sum/1. Two Sum.go | leetcode/0001.Two-Sum/1. Two Sum.go | package leetcode
func twoSum(nums []int, target int) []int {
m := make(map[int]int)
for k, v := range nums {
if idx, ok := m[target-v]; ok {
return []int{idx, k}
}
m[v] = k
}
return nil
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0594.Longest-Harmonious-Subsequence/594. Longest Harmonious Subsequence.go | leetcode/0594.Longest-Harmonious-Subsequence/594. Longest Harmonious Subsequence.go | package leetcode
func findLHS(nums []int) int {
if len(nums) < 2 {
return 0
}
res := make(map[int]int, len(nums))
for _, num := range nums {
if _, exist := res[num]; exist {
res[num]++
continue
}
res[num] = 1
}
longest := 0
for k, c := range res {
if n, exist := res[k+1]; exist {
if c+n > longest {
longest = c + n
}
}
}
return longest
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0594.Longest-Harmonious-Subsequence/594. Longest Harmonious Subsequence_test.go | leetcode/0594.Longest-Harmonious-Subsequence/594. Longest Harmonious Subsequence_test.go | package leetcode
import (
"fmt"
"testing"
)
type question594 struct {
para594
ans594
}
// para 是参数
// one 代表第一个参数
type para594 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans594 struct {
one int
}
func Test_Problem594(t *testing.T) {
qs := []question594{
{
para594{[]int{1, 3, 2, 2, 5, 2, 3, 7}},
ans594{5},
},
}
fmt.Printf("------------------------Leetcode Problem 594------------------------\n")
for _, q := range qs {
_, p := q.ans594, q.para594
fmt.Printf("【input】:%v 【output】:%v\n", p, findLHS(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/0753.Cracking-the-Safe/753. Cracking the Safe.go | leetcode/0753.Cracking-the-Safe/753. Cracking the Safe.go | package leetcode
import "math"
const number = "0123456789"
func crackSafe(n int, k int) string {
if n == 1 {
return number[:k]
}
visit, total := map[string]bool{}, int(math.Pow(float64(k), float64(n)))
str := make([]byte, 0, total+n-1)
for i := 1; i != n; i++ {
str = append(str, '0')
}
dfsCrackSafe(total, n, k, &str, &visit)
return string(str)
}
func dfsCrackSafe(depth, n, k int, str *[]byte, visit *map[string]bool) bool {
if depth == 0 {
return true
}
for i := 0; i != k; i++ {
*str = append(*str, byte('0'+i))
cur := string((*str)[len(*str)-n:])
if _, ok := (*visit)[cur]; ok != true {
(*visit)[cur] = true
if dfsCrackSafe(depth-1, n, k, str, visit) {
// 只有这里不需要删除
return true
}
delete(*visit, cur)
}
// 删除
*str = (*str)[0 : len(*str)-1]
}
return false
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0753.Cracking-the-Safe/753. Cracking the Safe_test.go | leetcode/0753.Cracking-the-Safe/753. Cracking the Safe_test.go | package leetcode
import (
"fmt"
"testing"
)
type question753 struct {
para753
ans753
}
// para 是参数
// one 代表第一个参数
type para753 struct {
n int
k int
}
// ans 是答案
// one 代表第一个答案
type ans753 struct {
one string
}
func Test_Problem753(t *testing.T) {
qs := []question753{
{
para753{1, 2},
ans753{"01"},
},
{
para753{2, 2},
ans753{"00110"},
},
}
fmt.Printf("------------------------Leetcode Problem 753------------------------\n")
for _, q := range qs {
_, p := q.ans753, q.para753
fmt.Printf("【input】:%v 【output】:%v\n", p, crackSafe(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/0728.Self-Dividing-Numbers/728.Self Dividing Numbers_test.go | leetcode/0728.Self-Dividing-Numbers/728.Self Dividing Numbers_test.go | package leetcode
import (
"fmt"
"testing"
)
type question728 struct {
para728
ans728
}
// para 是参数
type para728 struct {
left int
right int
}
// ans 是答案
type ans728 struct {
ans []int
}
func Test_Problem728(t *testing.T) {
qs := []question728{
{
para728{1, 22},
ans728{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22}},
},
{
para728{47, 85},
ans728{[]int{48, 55, 66, 77}},
},
}
fmt.Printf("------------------------Leetcode Problem 728------------------------\n")
for _, q := range qs {
_, p := q.ans728, q.para728
fmt.Printf("【input】:%v ", p)
fmt.Printf("【output】:%v \n", selfDividingNumbers(p.left, p.right))
}
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/0728.Self-Dividing-Numbers/728.Self Dividing Numbers.go | leetcode/0728.Self-Dividing-Numbers/728.Self Dividing Numbers.go | package leetcode
func selfDividingNumbers(left int, right int) []int {
var ans []int
for num := left; num <= right; num++ {
if selfDividingNum(num) {
ans = append(ans, num)
}
}
return ans
}
func selfDividingNum(num int) bool {
for d := num; d > 0; d = d / 10 {
reminder := d % 10
if reminder == 0 {
return false
}
if num%reminder != 0 {
return false
}
}
return true
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1305.All-Elements-in-Two-Binary-Search-Trees/1305. All Elements in Two Binary Search Trees_test.go | leetcode/1305.All-Elements-in-Two-Binary-Search-Trees/1305. All Elements in Two Binary Search Trees_test.go | package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question1305 struct {
para1305
ans1305
}
// para 是参数
// one 代表第一个参数
type para1305 struct {
root1 []int
root2 []int
}
// ans 是答案
// one 代表第一个答案
type ans1305 struct {
one []int
}
func Test_Problem1305(t *testing.T) {
qs := []question1305{
{
para1305{[]int{2, 1, 4}, []int{1, 0, 3}},
ans1305{[]int{0, 1, 1, 2, 3, 4}},
},
{
para1305{[]int{0, -10, 10}, []int{5, 1, 7, 0, 2}},
ans1305{[]int{-10, 0, 0, 1, 2, 5, 7, 10}},
},
{
para1305{[]int{}, []int{5, 1, 7, 0, 2}},
ans1305{[]int{0, 1, 2, 5, 7}},
},
{
para1305{[]int{0, -10, 10}, []int{}},
ans1305{[]int{-10, 0, 10}},
},
{
para1305{[]int{1, structures.NULL, 8}, []int{8, 1}},
ans1305{[]int{1, 1, 8, 8}},
},
}
fmt.Printf("------------------------Leetcode Problem 1305------------------------\n")
for _, q := range qs {
_, p := q.ans1305, q.para1305
fmt.Printf("【input】:%v ", p)
fmt.Printf("【output】:%v \n", getAllElements(structures.Ints2TreeNode(p.root1), structures.Ints2TreeNode(p.root2)))
}
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/1305.All-Elements-in-Two-Binary-Search-Trees/1305. All Elements in Two Binary Search Trees.go | leetcode/1305.All-Elements-in-Two-Binary-Search-Trees/1305. All Elements in Two Binary Search Trees.go | package leetcode
import (
"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
* }
*/
// 解法一 合并排序
func getAllElements(root1 *TreeNode, root2 *TreeNode) []int {
arr1 := inorderTraversal(root1)
arr2 := inorderTraversal(root2)
arr1 = append(arr1, make([]int, len(arr2))...)
merge(arr1, len(arr1)-len(arr2), arr2, len(arr2))
return arr1
}
// this is 94 solution
func inorderTraversal(root *TreeNode) []int {
var result []int
inorder(root, &result)
return result
}
func inorder(root *TreeNode, output *[]int) {
if root != nil {
inorder(root.Left, output)
*output = append(*output, root.Val)
inorder(root.Right, output)
}
}
// this is 88 solution
func merge(nums1 []int, m int, nums2 []int, n int) {
if m == 0 {
copy(nums1, nums2)
return
}
// 这里不需要,因为测试数据考虑到了第一个数组的空间问题
// for index := 0; index < n; index++ {
// nums1 = append(nums1, nums2[index])
// }
i := m - 1
j := n - 1
k := m + n - 1
// 从后面往前放,只需要循环一次即可
for ; i >= 0 && j >= 0; k-- {
if nums1[i] > nums2[j] {
nums1[k] = nums1[i]
i--
} else {
nums1[k] = nums2[j]
j--
}
}
for ; j >= 0; k-- {
nums1[k] = nums2[j]
j--
}
}
// 解法二 暴力遍历排序,时间复杂度高
func getAllElements1(root1 *TreeNode, root2 *TreeNode) []int {
arr := []int{}
arr = append(arr, preorderTraversal(root1)...)
arr = append(arr, preorderTraversal(root2)...)
sort.Ints(arr)
return arr
}
// this is 144 solution
func preorderTraversal(root *TreeNode) []int {
res := []int{}
if root != nil {
res = append(res, root.Val)
tmp := preorderTraversal(root.Left)
for _, t := range tmp {
res = append(res, t)
}
tmp = preorderTraversal(root.Right)
for _, t := range tmp {
res = append(res, t)
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0852.Peak-Index-in-a-Mountain-Array/852. Peak Index in a Mountain Array_test.go | leetcode/0852.Peak-Index-in-a-Mountain-Array/852. Peak Index in a Mountain Array_test.go | package leetcode
import (
"fmt"
"testing"
)
type question852 struct {
para852
ans852
}
// para 是参数
// one 代表第一个参数
type para852 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans852 struct {
one int
}
func Test_Problem852(t *testing.T) {
qs := []question852{
{
para852{[]int{0, 1, 0}},
ans852{1},
},
{
para852{[]int{0, 2, 1, 0}},
ans852{1},
},
}
fmt.Printf("------------------------Leetcode Problem 852------------------------\n")
for _, q := range qs {
_, p := q.ans852, q.para852
fmt.Printf("【input】:%v 【output】:%v\n", p, peakIndexInMountainArray(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/0852.Peak-Index-in-a-Mountain-Array/852. Peak Index in a Mountain Array.go | leetcode/0852.Peak-Index-in-a-Mountain-Array/852. Peak Index in a Mountain Array.go | package leetcode
// 解法一 二分
func peakIndexInMountainArray(A []int) int {
low, high := 0, len(A)-1
for low <= high {
mid := low + (high-low)>>1
if A[mid] > A[mid+1] && A[mid] > A[mid-1] {
return mid
}
if A[mid] > A[mid+1] && A[mid] < A[mid-1] {
high = mid - 1
}
if A[mid] < A[mid+1] && A[mid] > A[mid-1] {
low = mid + 1
}
}
return 0
}
// 解法二 二分
func peakIndexInMountainArray1(A []int) int {
low, high := 0, len(A)-1
for low < high {
mid := low + (high-low)>>1
// 如果 mid 较大,则左侧存在峰值,high = m,如果 mid + 1 较大,则右侧存在峰值,low = mid + 1
if A[mid] > A[mid+1] {
high = mid
} else {
low = mid + 1
}
}
return low
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0778.Swim-in-Rising-Water/778. Swim in Rising Water_test.go | leetcode/0778.Swim-in-Rising-Water/778. Swim in Rising Water_test.go | package leetcode
import (
"fmt"
"testing"
)
type question778 struct {
para778
ans778
}
// para 是参数
// one 代表第一个参数
type para778 struct {
grid [][]int
}
// ans 是答案
// one 代表第一个答案
type ans778 struct {
one int
}
func Test_Problem778(t *testing.T) {
qs := []question778{
{
para778{[][]int{{0, 2}, {1, 3}}},
ans778{3},
},
{
para778{[][]int{{0, 1, 2, 3, 4}, {24, 23, 22, 21, 5}, {12, 13, 14, 15, 16}, {11, 17, 18, 19, 20}, {10, 9, 8, 7, 6}}},
ans778{16},
},
}
fmt.Printf("------------------------Leetcode Problem 778------------------------\n")
for _, q := range qs {
_, p := q.ans778, q.para778
fmt.Printf("【input】:%v 【output】:%v\n", p, swimInWater(p.grid))
}
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/0778.Swim-in-Rising-Water/778. Swim in Rising Water.go | leetcode/0778.Swim-in-Rising-Water/778. Swim in Rising Water.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/template"
)
// 解法一 DFS + 二分
func swimInWater(grid [][]int) int {
row, col, flags, minWait, maxWait := len(grid), len(grid[0]), make([][]int, len(grid)), 0, 0
for i, row := range grid {
flags[i] = make([]int, len(row))
for j := 0; j < col; j++ {
flags[i][j] = -1
if row[j] > maxWait {
maxWait = row[j]
}
}
}
for minWait < maxWait {
midWait := (minWait + maxWait) / 2
addFlags(grid, flags, midWait, 0, 0)
if flags[row-1][col-1] == midWait {
maxWait = midWait
} else {
minWait = midWait + 1
}
}
return minWait
}
func addFlags(grid [][]int, flags [][]int, flag int, row int, col int) {
if row < 0 || col < 0 || row >= len(grid) || col >= len(grid[0]) {
return
}
if grid[row][col] > flag || flags[row][col] == flag {
return
}
flags[row][col] = flag
addFlags(grid, flags, flag, row-1, col)
addFlags(grid, flags, flag, row+1, col)
addFlags(grid, flags, flag, row, col-1)
addFlags(grid, flags, flag, row, col+1)
}
// 解法二 并查集(并不是此题的最优解)
func swimInWater1(grid [][]int) int {
n, uf, res := len(grid), template.UnionFind{}, 0
uf.Init(n * n)
for uf.Find(0) != uf.Find(n*n-1) {
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if grid[i][j] > res {
continue
}
if i < n-1 && grid[i+1][j] <= res {
uf.Union(i*n+j, i*n+j+n)
}
if j < n-1 && grid[i][j+1] <= res {
uf.Union(i*n+j, i*n+j+1)
}
}
}
res++
}
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/1073.Adding-Two-Negabinary-Numbers/1073. Adding Two Negabinary Numbers.go | leetcode/1073.Adding-Two-Negabinary-Numbers/1073. Adding Two Negabinary Numbers.go | package leetcode
// 解法一 模拟进位
func addNegabinary(arr1 []int, arr2 []int) []int {
carry, ans := 0, []int{}
for i, j := len(arr1)-1, len(arr2)-1; i >= 0 || j >= 0 || carry != 0; {
if i >= 0 {
carry += arr1[i]
i--
}
if j >= 0 {
carry += arr2[j]
j--
}
ans = append([]int{carry & 1}, ans...)
carry = -(carry >> 1)
}
for idx, num := range ans { // 去掉前导 0
if num != 0 {
return ans[idx:]
}
}
return []int{0}
}
// 解法二 标准的模拟,但是这个方法不能 AC,因为测试数据超过了 64 位,普通数据类型无法存储
func addNegabinary1(arr1 []int, arr2 []int) []int {
return intToNegabinary(negabinaryToInt(arr1) + negabinaryToInt(arr2))
}
func negabinaryToInt(arr []int) int {
if len(arr) == 0 {
return 0
}
res := 0
for i := 0; i < len(arr)-1; i++ {
if res == 0 {
res += (-2) * arr[i]
} else {
res = res * (-2)
res += (-2) * arr[i]
}
}
return res + 1*arr[len(arr)-1]
}
func intToNegabinary(num int) []int {
if num == 0 {
return []int{0}
}
res := []int{}
for num != 0 {
remainder := num % (-2)
num = num / (-2)
if remainder < 0 {
remainder += 2
num++
}
res = append([]int{remainder}, res...)
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1073.Adding-Two-Negabinary-Numbers/1073. Adding Two Negabinary Numbers_test.go | leetcode/1073.Adding-Two-Negabinary-Numbers/1073. Adding Two Negabinary Numbers_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1073 struct {
para1073
ans1073
}
// para 是参数
// one 代表第一个参数
type para1073 struct {
arr1 []int
arr2 []int
}
// ans 是答案
// one 代表第一个答案
type ans1073 struct {
one []int
}
func Test_Problem1073(t *testing.T) {
qs := []question1073{
{
para1073{[]int{1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 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1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1}},
},
{
para1073{[]int{0}, []int{1, 0, 0, 1}},
ans1073{[]int{1, 0, 0, 1}},
},
{
para1073{[]int{0}, []int{1, 1}},
ans1073{[]int{1, 1}},
},
{
para1073{[]int{1, 1, 1, 1, 1}, []int{1, 0, 1}},
ans1073{[]int{1, 0, 0, 0, 0}},
},
{
para1073{[]int{0}, []int{0}},
ans1073{[]int{0}},
},
{
para1073{[]int{0}, []int{1, 0}},
ans1073{[]int{1, 0}},
},
}
fmt.Printf("------------------------Leetcode Problem 1073------------------------\n")
for _, q := range qs {
_, p := q.ans1073, q.para1073
fmt.Printf("【input】:%v 【output】:%v\n", p, addNegabinary1(p.arr1, p.arr2))
}
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/0710.Random-Pick-with-Blacklist/710. Random Pick with Blacklist_test.go | leetcode/0710.Random-Pick-with-Blacklist/710. Random Pick with Blacklist_test.go | package leetcode
import (
"fmt"
"testing"
)
type question710 struct {
para710
ans710
}
// para 是参数
// one 代表第一个参数
type para710 struct {
n int
blackList []int
times int
}
// ans 是答案
// one 代表第一个答案
type ans710 struct {
one []int
}
func Test_Problem710(t *testing.T) {
qs := []question710{
{
para710{1, []int{}, 3},
ans710{[]int{0, 0, 0}},
},
{
para710{2, []int{}, 3},
ans710{[]int{1, 1, 1}},
},
{
para710{3, []int{1}, 3},
ans710{[]int{0, 0, 2}},
},
{
para710{4, []int{2}, 3},
ans710{[]int{1, 3, 1}},
},
{
para710{10000000, []int{1, 9999, 999999, 99999, 100, 0}, 10},
ans710{[]int{400, 200, 300}},
},
}
fmt.Printf("------------------------Leetcode Problem 710------------------------\n")
for _, q := range qs {
_, p := q.ans710, q.para710
fmt.Printf("【input】: n = %v blacklist = %v pick times = %v ", p.n, p.blackList, p.times)
obj := Constructor710(p.n, p.blackList)
fmt.Printf("【output】:")
for i := 0; i < p.times; i++ {
fmt.Printf(" %v ,", obj.Pick())
}
fmt.Printf("\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/0710.Random-Pick-with-Blacklist/710. Random Pick with Blacklist.go | leetcode/0710.Random-Pick-with-Blacklist/710. Random Pick with Blacklist.go | package leetcode
import "math/rand"
type Solution struct {
M int
BlackMap map[int]int
}
func Constructor710(N int, blacklist []int) Solution {
blackMap := map[int]int{}
for i := 0; i < len(blacklist); i++ {
blackMap[blacklist[i]] = 1
}
M := N - len(blacklist)
for _, value := range blacklist {
if value < M {
for {
if _, ok := blackMap[N-1]; ok {
N--
} else {
break
}
}
blackMap[value] = N - 1
N--
}
}
return Solution{BlackMap: blackMap, M: M}
}
func (this *Solution) Pick() int {
idx := rand.Intn(this.M)
if _, ok := this.BlackMap[idx]; ok {
return this.BlackMap[idx]
}
return idx
}
/**
* Your Solution object will be instantiated and called as such:
* obj := Constructor(N, blacklist);
* param_1 := obj.Pick();
*/
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0127.Word-Ladder/127. Word Ladder.go | leetcode/0127.Word-Ladder/127. Word Ladder.go | package leetcode
func ladderLength(beginWord string, endWord string, wordList []string) int {
wordMap, que, depth := getWordMap(wordList, beginWord), []string{beginWord}, 0
for len(que) > 0 {
depth++
qlen := len(que)
for i := 0; i < qlen; i++ {
word := que[0]
que = que[1:]
candidates := getCandidates(word)
for _, candidate := range candidates {
if _, ok := wordMap[candidate]; ok {
if candidate == endWord {
return depth + 1
}
delete(wordMap, candidate)
que = append(que, candidate)
}
}
}
}
return 0
}
func getWordMap(wordList []string, beginWord string) map[string]int {
wordMap := make(map[string]int)
for i, word := range wordList {
if _, ok := wordMap[word]; !ok {
if word != beginWord {
wordMap[word] = i
}
}
}
return wordMap
}
func getCandidates(word string) []string {
var res []string
for i := 0; i < 26; i++ {
for j := 0; j < len(word); j++ {
if word[j] != byte(int('a')+i) {
res = append(res, word[:j]+string(rune(int('a')+i))+word[j+1:])
}
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0127.Word-Ladder/127. Word Ladder_test.go | leetcode/0127.Word-Ladder/127. Word Ladder_test.go | package leetcode
import (
"fmt"
"testing"
)
type question127 struct {
para127
ans127
}
// para 是参数
// one 代表第一个参数
type para127 struct {
b string
e string
w []string
}
// ans 是答案
// one 代表第一个答案
type ans127 struct {
one int
}
func Test_Problem127(t *testing.T) {
qs := []question127{
{
para127{"hit", "cog", []string{"hot", "dot", "dog", "lot", "log", "cog"}},
ans127{5},
},
{
para127{"hit", "cog", []string{"hot", "dot", "dog", "lot", "log"}},
ans127{0},
},
}
fmt.Printf("------------------------Leetcode Problem 127------------------------\n")
for _, q := range qs {
_, p := q.ans127, q.para127
fmt.Printf("【input】:%v 【output】:%v\n", p, ladderLength(p.b, p.e, p.w))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0003.Longest-Substring-Without-Repeating-Characters/3. Longest Substring Without Repeating Characters.go | leetcode/0003.Longest-Substring-Without-Repeating-Characters/3. Longest Substring Without Repeating Characters.go | package leetcode
// 解法一 位图
func lengthOfLongestSubstring(s string) int {
if len(s) == 0 {
return 0
}
var bitSet [256]bool
result, left, right := 0, 0, 0
for left < len(s) {
// 右侧字符对应的 bitSet 被标记 true,说明此字符在 X 位置重复,需要左侧向前移动,直到将 X 标记为 false
if bitSet[s[right]] {
bitSet[s[left]] = false
left++
} else {
bitSet[s[right]] = true
right++
}
if result < right-left {
result = right - left
}
if left+result >= len(s) || right >= len(s) {
break
}
}
return result
}
// 解法二 滑动窗口
func lengthOfLongestSubstring1(s string) int {
if len(s) == 0 {
return 0
}
var freq [127]int
result, left, right := 0, 0, -1
for left < len(s) {
if right+1 < len(s) && freq[s[right+1]] == 0 {
freq[s[right+1]]++
right++
} else {
freq[s[left]]--
left++
}
result = max(result, right-left+1)
}
return result
}
// 解法三 滑动窗口-哈希桶
func lengthOfLongestSubstring2(s string) int {
right, left, res := 0, 0, 0
indexes := make(map[byte]int, len(s))
for left < len(s) {
if idx, ok := indexes[s[left]]; ok && idx >= right {
right = idx + 1
}
indexes[s[left]] = left
left++
res = max(res, left-right)
}
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/0003.Longest-Substring-Without-Repeating-Characters/3. Longest Substring Without Repeating Characters_test.go | leetcode/0003.Longest-Substring-Without-Repeating-Characters/3. Longest Substring Without Repeating Characters_test.go | package leetcode
import (
"fmt"
"testing"
)
type question3 struct {
para3
ans3
}
// para 是参数
// one 代表第一个参数
type para3 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans3 struct {
one int
}
func Test_Problem3(t *testing.T) {
qs := []question3{
{
para3{"abcabcbb"},
ans3{3},
},
{
para3{"bbbbb"},
ans3{1},
},
{
para3{"pwwkew"},
ans3{3},
},
{
para3{""},
ans3{0},
},
}
fmt.Printf("------------------------Leetcode Problem 3------------------------\n")
for _, q := range qs {
_, p := q.ans3, q.para3
fmt.Printf("【input】:%v 【output】:%v\n", p, lengthOfLongestSubstring(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/0704.Binary-Search/704. Binary Search.go | leetcode/0704.Binary-Search/704. Binary Search.go | package leetcode
func search704(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + (high-low)>>1
if nums[mid] == target {
return mid
} else if nums[mid] > target {
high = mid - 1
} else {
low = mid + 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/0704.Binary-Search/704. Binary Search_test.go | leetcode/0704.Binary-Search/704. Binary Search_test.go | package leetcode
import (
"fmt"
"testing"
)
type question704 struct {
para704
ans704
}
// para 是参数
// one 代表第一个参数
type para704 struct {
nums []int
target int
}
// ans 是答案
// one 代表第一个答案
type ans704 struct {
one int
}
func Test_Problem704(t *testing.T) {
qs := []question704{
{
para704{[]int{-1, 0, 3, 5, 9, 12}, 9},
ans704{4},
},
{
para704{[]int{-1, 0, 3, 5, 9, 12}, 2},
ans704{-1},
},
}
fmt.Printf("------------------------Leetcode Problem 704------------------------\n")
for _, q := range qs {
_, p := q.ans704, q.para704
fmt.Printf("【input】:%v 【output】:%v\n", p, search704(p.nums, p.target))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1185.Day-of-the-Week/1185. Day of the Week_test.go | leetcode/1185.Day-of-the-Week/1185. Day of the Week_test.go | package leetcode
import (
"fmt"
"testing"
)
type question1185 struct {
para1185
ans1185
}
// para 是参数
// one 代表第一个参数
type para1185 struct {
day int
month int
year int
}
// ans 是答案
// one 代表第一个答案
type ans1185 struct {
one string
}
func Test_Problem1185(t *testing.T) {
qs := []question1185{
{
para1185{31, 8, 2019},
ans1185{"Saturday"},
},
{
para1185{18, 7, 1999},
ans1185{"Sunday"},
},
{
para1185{15, 8, 1993},
ans1185{"Sunday"},
},
}
fmt.Printf("------------------------Leetcode Problem 1185------------------------\n")
for _, q := range qs {
_, p := q.ans1185, q.para1185
fmt.Printf("【input】:%v 【output】:%v\n", p, dayOfTheWeek(p.day, p.month, p.year))
}
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/1185.Day-of-the-Week/1185. Day of the Week.go | leetcode/1185.Day-of-the-Week/1185. Day of the Week.go | package leetcode
import "time"
func dayOfTheWeek(day int, month int, year int) string {
return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.Local).Weekday().String()
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0016.3Sum-Closest/16. 3Sum Closest.go | leetcode/0016.3Sum-Closest/16. 3Sum Closest.go | package leetcode
import (
"math"
"sort"
)
// 解法一 O(n^2)
func threeSumClosest(nums []int, target int) int {
n, res, diff := len(nums), 0, math.MaxInt32
if n > 2 {
sort.Ints(nums)
for i := 0; i < n-2; i++ {
if i > 0 && nums[i] == nums[i-1] {
continue
}
for j, k := i+1, n-1; j < k; {
sum := nums[i] + nums[j] + nums[k]
if abs(sum-target) < diff {
res, diff = sum, abs(sum-target)
}
if sum == target {
return res
} else if sum > target {
k--
} else {
j++
}
}
}
}
return res
}
// 解法二 暴力解法 O(n^3)
func threeSumClosest1(nums []int, target int) int {
res, difference := 0, math.MaxInt16
for i := 0; i < len(nums); i++ {
for j := i + 1; j < len(nums); j++ {
for k := j + 1; k < len(nums); k++ {
if abs(nums[i]+nums[j]+nums[k]-target) < difference {
difference = abs(nums[i] + nums[j] + nums[k] - target)
res = nums[i] + nums[j] + nums[k]
}
}
}
}
return res
}
func abs(a int) int {
if a > 0 {
return a
}
return -a
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0016.3Sum-Closest/16. 3Sum Closest_test.go | leetcode/0016.3Sum-Closest/16. 3Sum Closest_test.go | package leetcode
import (
"fmt"
"testing"
)
type question16 struct {
para16
ans16
}
// para 是参数
// one 代表第一个参数
type para16 struct {
a []int
target int
}
// ans 是答案
// one 代表第一个答案
type ans16 struct {
one int
}
func Test_Problem16(t *testing.T) {
qs := []question16{
{
para16{[]int{-1, 0, 1, 1, 55}, 3},
ans16{2},
},
{
para16{[]int{0, 0, 0}, 1},
ans16{0},
},
{
para16{[]int{-1, 2, 1, -4}, 1},
ans16{2},
},
{
para16{[]int{1, 1, -1}, 0},
ans16{1},
},
{
para16{[]int{-1, 2, 1, -4}, 1},
ans16{2},
},
}
fmt.Printf("------------------------Leetcode Problem 16------------------------\n")
for _, q := range qs {
_, p := q.ans16, q.para16
fmt.Printf("【input】:%v 【output】:%v\n", p, threeSumClosest(p.a, p.target))
}
fmt.Printf("\n\n\n")
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0952.Largest-Component-Size-by-Common-Factor/952. Largest Component Size by Common Factor_test.go | leetcode/0952.Largest-Component-Size-by-Common-Factor/952. Largest Component Size by Common Factor_test.go | package leetcode
import (
"fmt"
"testing"
)
type question952 struct {
para952
ans952
}
// para 是参数
// one 代表第一个参数
type para952 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans952 struct {
one int
}
func Test_Problem952(t *testing.T) {
qs := []question952{
{
para952{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9}},
ans952{6},
},
{
para952{[]int{4, 6, 15, 35}},
ans952{4},
},
{
para952{[]int{20, 50, 9, 63}},
ans952{2},
},
{
para952{[]int{2, 3, 6, 7, 4, 12, 21, 39}},
ans952{8},
},
}
fmt.Printf("------------------------Leetcode Problem 952------------------------\n")
for _, q := range qs {
_, p := q.ans952, q.para952
fmt.Printf("【input】:%v 【output】:%v\n", p, largestComponentSize(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/0952.Largest-Component-Size-by-Common-Factor/952. Largest Component Size by Common Factor.go | leetcode/0952.Largest-Component-Size-by-Common-Factor/952. Largest Component Size by Common Factor.go | package leetcode
import (
"github.com/halfrost/LeetCode-Go/template"
)
// 解法一 并查集 UnionFind
func largestComponentSize(A []int) int {
maxElement, uf, countMap, res := 0, template.UnionFind{}, map[int]int{}, 1
for _, v := range A {
maxElement = max(maxElement, v)
}
uf.Init(maxElement + 1)
for _, v := range A {
for k := 2; k*k <= v; k++ {
if v%k == 0 {
uf.Union(v, k)
uf.Union(v, v/k)
}
}
}
for _, v := range A {
countMap[uf.Find(v)]++
res = max(res, countMap[uf.Find(v)])
}
return res
}
// 解法二 UnionFindCount
func largestComponentSize1(A []int) int {
uf, factorMap := template.UnionFindCount{}, map[int]int{}
uf.Init(len(A))
for i, v := range A {
for k := 2; k*k <= v; k++ {
if v%k == 0 {
if _, ok := factorMap[k]; !ok {
factorMap[k] = i
} else {
uf.Union(i, factorMap[k])
}
if _, ok := factorMap[v/k]; !ok {
factorMap[v/k] = i
} else {
uf.Union(i, factorMap[v/k])
}
}
}
if _, ok := factorMap[v]; !ok {
factorMap[v] = i
} else {
uf.Union(i, factorMap[v])
}
}
return uf.MaxUnionCount()
}
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/0125.Valid-Palindrome/125. Valid Palindrome.go | leetcode/0125.Valid-Palindrome/125. Valid Palindrome.go | package leetcode
import (
"strings"
)
func isPalindrome(s string) bool {
s = strings.ToLower(s)
i, j := 0, len(s)-1
for i < j {
for i < j && !isChar(s[i]) {
i++
}
for i < j && !isChar(s[j]) {
j--
}
if s[i] != s[j] {
return false
}
i++
j--
}
return true
}
// 判断 c 是否是字符或者数字
func isChar(c byte) bool {
if ('a' <= c && c <= 'z') || ('0' <= c && c <= '9') {
return true
}
return false
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0125.Valid-Palindrome/125. Valid Palindrome_test.go | leetcode/0125.Valid-Palindrome/125. Valid Palindrome_test.go | package leetcode
import (
"fmt"
"testing"
)
func Test_Problem125(t *testing.T) {
tcs := []struct {
s string
ans bool
}{
{
"0p",
false,
},
{
"0",
true,
},
{
"race a car",
false,
},
{
"A man, a plan, a canal: Panama",
true,
},
}
fmt.Printf("------------------------Leetcode Problem 125------------------------\n")
for _, tc := range tcs {
fmt.Printf("【input】:%v 【output】:%v\n", tc, isPalindrome(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/0609.Find-Duplicate-File-in-System/609. Find Duplicate File in System_test.go | leetcode/0609.Find-Duplicate-File-in-System/609. Find Duplicate File in System_test.go | package leetcode
import (
"fmt"
"testing"
)
type question609 struct {
para609
ans609
}
// para 是参数
// one 代表第一个参数
type para609 struct {
paths []string
}
// ans 是答案
// one 代表第一个答案
type ans609 struct {
one [][]string
}
func Test_Problem609(t *testing.T) {
qs := []question609{
{
para609{[]string{"root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"}},
ans609{[][]string{{"root/a/2.txt", "root/c/d/4.txt", "root/4.txt"}, {"root/a/1.txt", "root/c/3.txt"}}},
},
{
para609{[]string{"root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)"}},
ans609{[][]string{{"root/a/2.txt", "root/c/d/4.txt"}, {"root/a/1.txt", "root/c/3.txt"}}},
},
}
fmt.Printf("------------------------Leetcode Problem 609------------------------\n")
for _, q := range qs {
_, p := q.ans609, q.para609
fmt.Printf("【input】:%v 【output】:%v\n", p, findDuplicate(p.paths))
}
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/0609.Find-Duplicate-File-in-System/609. Find Duplicate File in System.go | leetcode/0609.Find-Duplicate-File-in-System/609. Find Duplicate File in System.go | package leetcode
import "strings"
func findDuplicate(paths []string) [][]string {
cache := make(map[string][]string)
for _, path := range paths {
parts := strings.Split(path, " ")
dir := parts[0]
for i := 1; i < len(parts); i++ {
bracketPosition := strings.IndexByte(parts[i], '(')
content := parts[i][bracketPosition+1 : len(parts[i])-1]
cache[content] = append(cache[content], dir+"/"+parts[i][:bracketPosition])
}
}
res := make([][]string, 0, len(cache))
for _, group := range cache {
if len(group) >= 2 {
res = append(res, group)
}
}
return res
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0036.Valid-Sudoku/36. Valid Sudoku_test.go | leetcode/0036.Valid-Sudoku/36. Valid Sudoku_test.go | package leetcode
import (
"fmt"
"testing"
)
type question36 struct {
para36
ans36
}
// para 是参数
// one 代表第一个参数
type para36 struct {
s [][]byte
}
// ans 是答案
// one 代表第一个答案
type ans36 struct {
s bool
}
func Test_Problem36(t *testing.T) {
qs := []question36{
{
para36{[][]byte{
{'5', '3', '.', '.', '7', '.', '.', '.', '.'},
{'6', '.', '.', '1', '9', '5', '.', '.', '.'},
{'.', '9', '8', '.', '.', '.', '.', '6', '.'},
{'8', '.', '.', '.', '6', '.', '.', '.', '3'},
{'4', '.', '.', '8', '.', '3', '.', '.', '1'},
{'7', '.', '.', '.', '2', '.', '.', '.', '6'},
{'.', '6', '.', '.', '.', '.', '2', '8', '.'},
{'.', '.', '.', '4', '1', '9', '.', '.', '5'},
{'.', '.', '.', '.', '8', '.', '.', '7', '9'}}},
ans36{true},
},
{
para36{[][]byte{
{'8', '3', '.', '.', '7', '.', '.', '.', '.'},
{'6', '.', '.', '1', '9', '5', '.', '.', '.'},
{'.', '9', '8', '.', '.', '.', '.', '6', '.'},
{'8', '.', '.', '.', '6', '.', '.', '.', '3'},
{'4', '.', '.', '8', '.', '3', '.', '.', '1'},
{'7', '.', '.', '.', '2', '.', '.', '.', '6'},
{'.', '6', '.', '.', '.', '.', '2', '8', '.'},
{'.', '.', '.', '4', '1', '9', '.', '.', '5'},
{'.', '.', '.', '.', '8', '.', '.', '7', '9'}}},
ans36{false},
},
{
para36{[][]byte{
{'.', '8', '7', '6', '5', '4', '3', '2', '1'},
{'2', '.', '.', '.', '.', '.', '.', '.', '.'},
{'3', '.', '.', '.', '.', '.', '.', '.', '.'},
{'4', '.', '.', '.', '.', '.', '.', '.', '.'},
{'5', '.', '.', '.', '.', '.', '.', '.', '.'},
{'6', '.', '.', '.', '.', '.', '.', '.', '.'},
{'7', '.', '.', '.', '.', '.', '.', '.', '.'},
{'8', '.', '.', '.', '.', '.', '.', '.', '.'},
{'9', '.', '.', '.', '.', '.', '.', '.', '.'}}},
ans36{true},
},
}
fmt.Printf("------------------------Leetcode Problem 36------------------------\n")
for _, q := range qs {
_, p := q.ans36, q.para36
fmt.Printf("【input】:%v 【output】:%v\n", p, isValidSudoku1(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/0036.Valid-Sudoku/36. Valid Sudoku.go | leetcode/0036.Valid-Sudoku/36. Valid Sudoku.go | package leetcode
import "strconv"
// 解法一 暴力遍历,时间复杂度 O(n^3)
func isValidSudoku(board [][]byte) bool {
// 判断行 row
for i := 0; i < 9; i++ {
tmp := [10]int{}
for j := 0; j < 9; j++ {
cellVal := board[i][j : j+1]
if string(cellVal) != "." {
index, _ := strconv.Atoi(string(cellVal))
if index > 9 || index < 1 {
return false
}
if tmp[index] == 1 {
return false
}
tmp[index] = 1
}
}
}
// 判断列 column
for i := 0; i < 9; i++ {
tmp := [10]int{}
for j := 0; j < 9; j++ {
cellVal := board[j][i]
if string(cellVal) != "." {
index, _ := strconv.Atoi(string(cellVal))
if index > 9 || index < 1 {
return false
}
if tmp[index] == 1 {
return false
}
tmp[index] = 1
}
}
}
// 判断 9宫格 3X3 cell
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
tmp := [10]int{}
for ii := i * 3; ii < i*3+3; ii++ {
for jj := j * 3; jj < j*3+3; jj++ {
cellVal := board[ii][jj]
if string(cellVal) != "." {
index, _ := strconv.Atoi(string(cellVal))
if tmp[index] == 1 {
return false
}
tmp[index] = 1
}
}
}
}
}
return true
}
// 解法二 添加缓存,时间复杂度 O(n^2)
func isValidSudoku1(board [][]byte) bool {
rowbuf, colbuf, boxbuf := make([][]bool, 9), make([][]bool, 9), make([][]bool, 9)
for i := 0; i < 9; i++ {
rowbuf[i] = make([]bool, 9)
colbuf[i] = make([]bool, 9)
boxbuf[i] = make([]bool, 9)
}
// 遍历一次,添加缓存
for r := 0; r < 9; r++ {
for c := 0; c < 9; c++ {
if board[r][c] != '.' {
num := board[r][c] - '0' - byte(1)
if rowbuf[r][num] || colbuf[c][num] || boxbuf[r/3*3+c/3][num] {
return false
}
rowbuf[r][num] = true
colbuf[c][num] = true
boxbuf[r/3*3+c/3][num] = true // r,c 转换到box方格中
}
}
}
return true
}
| go | MIT | d78a9e0927a302038992428433d2eb450efd93a2 | 2026-01-07T08:36:06.754118Z | false |
halfrost/LeetCode-Go | https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0032.Longest-Valid-Parentheses/32. Longest Valid Parentheses_test.go | leetcode/0032.Longest-Valid-Parentheses/32. Longest Valid Parentheses_test.go | package leetcode
import (
"fmt"
"testing"
)
type question32 struct {
para32
ans32
}
// para 是参数
// one 代表第一个参数
type para32 struct {
s string
}
// ans 是答案
// one 代表第一个答案
type ans32 struct {
one int
}
func Test_Problem32(t *testing.T) {
qs := []question32{
{
para32{"(()"},
ans32{2},
},
{
para32{")()())"},
ans32{4},
},
{
para32{"()(())"},
ans32{6},
},
{
para32{"()(())))"},
ans32{6},
},
{
para32{"()(()"},
ans32{2},
},
}
fmt.Printf("------------------------Leetcode Problem 32------------------------\n")
for _, q := range qs {
_, p := q.ans32, q.para32
fmt.Printf("【input】:%v 【output】:%v\n", p, longestValidParentheses(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/0032.Longest-Valid-Parentheses/32. Longest Valid Parentheses.go | leetcode/0032.Longest-Valid-Parentheses/32. Longest Valid Parentheses.go | package leetcode
// 解法一 栈
func longestValidParentheses(s string) int {
stack, res := []int{}, 0
stack = append(stack, -1)
for i := 0; i < len(s); i++ {
if s[i] == '(' {
stack = append(stack, i)
} else {
stack = stack[:len(stack)-1]
if len(stack) == 0 {
stack = append(stack, i)
} else {
res = max(res, i-stack[len(stack)-1])
}
}
}
return res
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
// 解法二 双指针
func longestValidParentheses1(s string) int {
left, right, maxLength := 0, 0, 0
for i := 0; i < len(s); i++ {
if s[i] == '(' {
left++
} else {
right++
}
if left == right {
maxLength = max(maxLength, 2*right)
} else if right > left {
left, right = 0, 0
}
}
left, right = 0, 0
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '(' {
left++
} else {
right++
}
if left == right {
maxLength = max(maxLength, 2*left)
} else if left > right {
left, right = 0, 0
}
}
return maxLength
}
| 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.