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/0825.Friends-Of-Appropriate-Ages/825. Friends Of Appropriate Ages_test.go
leetcode/0825.Friends-Of-Appropriate-Ages/825. Friends Of Appropriate Ages_test.go
package leetcocde import ( "fmt" "testing" ) type question825 struct { para825 ans825 } // para 是参数 // one 代表第一个参数 type para825 struct { ages []int } // ans 是答案 // one 代表第一个答案 type ans825 struct { one int } func Test_Problem825(t *testing.T) { qs := []question825{ { para825{[]int{16, 16}}, ans825{2}, }, { para825{[]int{16, 17, 18}}, ans825{2}, }, { para825{[]int{20, 30, 100, 110, 120}}, ans825{3}, }, } fmt.Printf("------------------------Leetcode Problem 825------------------------\n") for _, q := range qs { _, p := q.ans825, q.para825 fmt.Printf("【input】:%v 【output】:%v\n", p, numFriendRequests(p.ages)) } 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/0825.Friends-Of-Appropriate-Ages/825. Friends Of Appropriate Ages.go
leetcode/0825.Friends-Of-Appropriate-Ages/825. Friends Of Appropriate Ages.go
package leetcocde import "sort" // 解法一 前缀和,时间复杂度 O(n) func numFriendRequests(ages []int) int { count, prefixSum, res := make([]int, 121), make([]int, 121), 0 for _, age := range ages { count[age]++ } for i := 1; i < 121; i++ { prefixSum[i] = prefixSum[i-1] + count[i] } for i := 15; i < 121; i++ { if count[i] > 0 { bound := i/2 + 8 res += count[i] * (prefixSum[i] - prefixSum[bound-1] - 1) } } return res } // 解法二 双指针 + 排序,时间复杂度 O(n logn) func numFriendRequests1(ages []int) int { sort.Ints(ages) left, right, res := 0, 0, 0 for _, age := range ages { if age < 15 { continue } for ages[left]*2 <= age+14 { left++ } for right+1 < len(ages) && ages[right+1] <= age { right++ } res += right - left } return res } // 解法三 暴力解法 O(n^2) func numFriendRequests2(ages []int) int { res, count := 0, [125]int{} for _, x := range ages { count[x]++ } for i := 1; i <= 120; i++ { for j := 1; j <= 120; j++ { if j > i { continue } if (j-7)*2 <= i { continue } if j > 100 && i < 100 { continue } if i != j { res += count[i] * count[j] } else { res += count[i] * (count[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/1646.Get-Maximum-in-Generated-Array/1646. Get Maximum in Generated Array.go
leetcode/1646.Get-Maximum-in-Generated-Array/1646. Get Maximum in Generated Array.go
package leetcode func getMaximumGenerated(n int) int { if n == 0 { return 0 } nums, max := make([]int, n+1), 0 nums[0], nums[1] = 0, 1 for i := 0; i <= n; i++ { if nums[i] > max { max = nums[i] } if 2*i >= 2 && 2*i <= n { nums[2*i] = nums[i] } if 2*i+1 >= 2 && 2*i+1 <= n { nums[2*i+1] = nums[i] + nums[i+1] } } return max }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1646.Get-Maximum-in-Generated-Array/1646. Get Maximum in Generated Array_test.go
leetcode/1646.Get-Maximum-in-Generated-Array/1646. Get Maximum in Generated Array_test.go
package leetcode import ( "fmt" "testing" ) type question1646 struct { para1646 ans1646 } // para 是参数 // one 代表第一个参数 type para1646 struct { n int } // ans 是答案 // one 代表第一个答案 type ans1646 struct { one int } func Test_Problem1646(t *testing.T) { qs := []question1646{ { para1646{7}, ans1646{3}, }, { para1646{2}, ans1646{1}, }, { para1646{3}, ans1646{2}, }, { para1646{0}, ans1646{0}, }, { para1646{1}, ans1646{1}, }, } fmt.Printf("------------------------Leetcode Problem 1646------------------------\n") for _, q := range qs { _, p := q.ans1646, q.para1646 fmt.Printf("【input】:%v 【output】:%v \n", p, getMaximumGenerated(p.n)) } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0878.Nth-Magical-Number/878. Nth Magical Number.go
leetcode/0878.Nth-Magical-Number/878. Nth Magical Number.go
package leetcode func nthMagicalNumber(N int, A int, B int) int { low, high := int64(0), int64(1*1e14) for low < high { mid := low + (high-low)>>1 if calNthMagicalCount(mid, int64(A), int64(B)) < int64(N) { low = mid + 1 } else { high = mid } } return int(low) % 1000000007 } func calNthMagicalCount(num, a, b int64) int64 { ab := a * b / gcd(a, b) return num/a + num/b - num/ab } func gcd(a, b int64) int64 { for b != 0 { a, b = b, a%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/0878.Nth-Magical-Number/878. Nth Magical Number_test.go
leetcode/0878.Nth-Magical-Number/878. Nth Magical Number_test.go
package leetcode import ( "fmt" "testing" ) type question878 struct { para878 ans878 } // para 是参数 // one 代表第一个参数 type para878 struct { n int a int b int } // ans 是答案 // one 代表第一个答案 type ans878 struct { one int } func Test_Problem878(t *testing.T) { qs := []question878{ { para878{1, 2, 3}, ans878{2}, }, { para878{4, 2, 3}, ans878{6}, }, { para878{5, 2, 4}, ans878{10}, }, { para878{3, 6, 4}, ans878{8}, }, { para878{1000000000, 40000, 40000}, ans878{999720007}, }, } fmt.Printf("------------------------Leetcode Problem 878------------------------\n") for _, q := range qs { _, p := q.ans878, q.para878 fmt.Printf("【input】:%v 【output】:%v\n", p, nthMagicalNumber(p.n, p.a, p.b)) } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1293.Shortest-Path-in-a-Grid-with-Obstacles-Elimination/1293. Shortest Path in a Grid with Obstacles Elimination.go
leetcode/1293.Shortest-Path-in-a-Grid-with-Obstacles-Elimination/1293. Shortest Path in a Grid with Obstacles Elimination.go
package leetcode var dir = [][]int{ {-1, 0}, {0, 1}, {1, 0}, {0, -1}, } type pos struct { x, y int obstacle int step int } func shortestPath(grid [][]int, k int) int { queue, m, n := []pos{}, len(grid), len(grid[0]) visitor := make([][][]int, m) if len(grid) == 1 && len(grid[0]) == 1 { return 0 } for i := 0; i < m; i++ { visitor[i] = make([][]int, n) for j := 0; j < n; j++ { visitor[i][j] = make([]int, k+1) } } visitor[0][0][0] = 1 queue = append(queue, pos{x: 0, y: 0, obstacle: 0, step: 0}) for len(queue) > 0 { size := len(queue) for size > 0 { size-- node := queue[0] queue = queue[1:] for i := 0; i < len(dir); i++ { newX := node.x + dir[i][0] newY := node.y + dir[i][1] if newX == m-1 && newY == n-1 { if node.obstacle != 0 { if node.obstacle <= k { return node.step + 1 } else { continue } } return node.step + 1 } if isInBoard(grid, newX, newY) { if grid[newX][newY] == 1 { if node.obstacle+1 <= k && visitor[newX][newY][node.obstacle+1] != 1 { queue = append(queue, pos{x: newX, y: newY, obstacle: node.obstacle + 1, step: node.step + 1}) visitor[newX][newY][node.obstacle+1] = 1 } } else { if node.obstacle <= k && visitor[newX][newY][node.obstacle] != 1 { queue = append(queue, pos{x: newX, y: newY, obstacle: node.obstacle, step: node.step + 1}) visitor[newX][newY][node.obstacle] = 1 } } } } } } return -1 } func isInBoard(board [][]int, x, y int) bool { return x >= 0 && x < len(board) && y >= 0 && y < len(board[0]) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1293.Shortest-Path-in-a-Grid-with-Obstacles-Elimination/1293. Shortest Path in a Grid with Obstacles Elimination_test.go
leetcode/1293.Shortest-Path-in-a-Grid-with-Obstacles-Elimination/1293. Shortest Path in a Grid with Obstacles Elimination_test.go
package leetcode import ( "fmt" "testing" ) type question1293 struct { para1293 ans1293 } // para 是参数 // one 代表第一个参数 type para1293 struct { grid [][]int k int } // ans 是答案 // one 代表第一个答案 type ans1293 struct { one int } func Test_Problem1293(t *testing.T) { qs := []question1293{ { para1293{[][]int{ {0, 0, 0}, }, 1}, ans1293{2}, }, { para1293{[][]int{ {0, 1, 1}, {0, 1, 1}, {0, 0, 0}, {0, 1, 0}, {0, 1, 0}, }, 2}, ans1293{6}, }, { para1293{[][]int{ {0, 0, 0}, {1, 1, 0}, {0, 0, 0}, {0, 1, 1}, {0, 0, 0}, }, 1}, ans1293{6}, }, { para1293{[][]int{ {0, 1, 1}, {1, 1, 1}, {1, 0, 0}, }, 1}, ans1293{-1}, }, { para1293{[][]int{ {0}, }, 1}, ans1293{0}, }, } fmt.Printf("------------------------Leetcode Problem 1293------------------------\n") for _, q := range qs { _, p := q.ans1293, q.para1293 fmt.Printf("【input】:%v 【output】:%v\n", p, shortestPath(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/1005.Maximize-Sum-Of-Array-After-K-Negations/1005. Maximize Sum Of Array After K Negations.go
leetcode/1005.Maximize-Sum-Of-Array-After-K-Negations/1005. Maximize Sum Of Array After K Negations.go
package leetcode import ( "sort" ) func largestSumAfterKNegations(A []int, K int) int { sort.Ints(A) minIdx := 0 for i := 0; i < K; i++ { A[minIdx] = -A[minIdx] if A[minIdx+1] < A[minIdx] { minIdx++ } } sum := 0 for _, a := range A { sum += a } return sum }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1005.Maximize-Sum-Of-Array-After-K-Negations/1005. Maximize Sum Of Array After K Negations_test.go
leetcode/1005.Maximize-Sum-Of-Array-After-K-Negations/1005. Maximize Sum Of Array After K Negations_test.go
package leetcode import ( "fmt" "testing" ) type question1005 struct { para1005 ans1005 } // para 是参数 // one 代表第一个参数 type para1005 struct { one []int two int } // ans 是答案 // one 代表第一个答案 type ans1005 struct { one int } func Test_Problem1005(t *testing.T) { qs := []question1005{ { para1005{[]int{4, 2, 3}, 1}, ans1005{5}, }, { para1005{[]int{3, -1, 0, 2}, 3}, ans1005{6}, }, { para1005{[]int{2, -3, -1, 5, -4}, 2}, ans1005{13}, }, { para1005{[]int{-2, 9, 9, 8, 4}, 5}, ans1005{32}, }, { para1005{[]int{5, -7, -8, -3, 9, 5, -5, -7}, 7}, ans1005{49}, }, { para1005{[]int{5, 6, 9, -3, 3}, 2}, ans1005{20}, }, { para1005{[]int{8, -7, -3, -9, 1, 9, -6, -9, 3}, 8}, ans1005{53}, }, } fmt.Printf("------------------------Leetcode Problem 1005------------------------\n") for _, q := range qs { _, p := q.ans1005, q.para1005 fmt.Printf("【input】:%v 【output】:%v\n", p, largestSumAfterKNegations(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/0014.Longest-Common-Prefix/14.Longest Common Prefix_test.go
leetcode/0014.Longest-Common-Prefix/14.Longest Common Prefix_test.go
package leetcode import ( "fmt" "testing" ) type question14 struct { para14 ans14 } // para 是参数 type para14 struct { strs []string } // ans 是答案 type ans14 struct { ans string } func Test_Problem14(t *testing.T) { qs := []question14{ { para14{[]string{"flower", "flow", "flight"}}, ans14{"fl"}, }, { para14{[]string{"dog", "racecar", "car"}}, ans14{""}, }, { para14{[]string{"ab", "a"}}, ans14{"a"}, }, } fmt.Printf("------------------------Leetcode Problem 14------------------------\n") for _, q := range qs { _, p := q.ans14, q.para14 fmt.Printf("【input】:%v 【output】:%v\n", p.strs, longestCommonPrefix(p.strs)) } 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/0014.Longest-Common-Prefix/14.Longest Common Prefix.go
leetcode/0014.Longest-Common-Prefix/14.Longest Common Prefix.go
package leetcode func longestCommonPrefix(strs []string) string { prefix := strs[0] for i := 1; i < len(strs); i++ { for j := 0; j < len(prefix); j++ { if len(strs[i]) <= j || strs[i][j] != prefix[j] { prefix = prefix[0:j] break } } } return prefix }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1619.Mean-of-Array-After-Removing-Some-Elements/1619. Mean of Array After Removing Some Elements.go
leetcode/1619.Mean-of-Array-After-Removing-Some-Elements/1619. Mean of Array After Removing Some Elements.go
package leetcode import "sort" func trimMean(arr []int) float64 { sort.Ints(arr) n, sum := len(arr), 0 for i := n / 20; i < n-(n/20); i++ { sum += arr[i] } return float64(sum) / float64((n - (n / 10))) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1619.Mean-of-Array-After-Removing-Some-Elements/1619. Mean of Array After Removing Some Elements_test.go
leetcode/1619.Mean-of-Array-After-Removing-Some-Elements/1619. Mean of Array After Removing Some Elements_test.go
package leetcode import ( "fmt" "testing" ) type question1619 struct { para1619 ans1619 } // para 是参数 // one 代表第一个参数 type para1619 struct { p []int } // ans 是答案 // one 代表第一个答案 type ans1619 struct { one float64 } func Test_Problem1619(t *testing.T) { qs := []question1619{ { para1619{[]int{1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3}}, ans1619{2.00000}, }, { para1619{[]int{6, 2, 7, 5, 1, 2, 0, 3, 10, 2, 5, 0, 5, 5, 0, 8, 7, 6, 8, 0}}, ans1619{4.00000}, }, { para1619{[]int{6, 0, 7, 0, 7, 5, 7, 8, 3, 4, 0, 7, 8, 1, 6, 8, 1, 1, 2, 4, 8, 1, 9, 5, 4, 3, 8, 5, 10, 8, 6, 6, 1, 0, 6, 10, 8, 2, 3, 4}}, ans1619{4.77778}, }, { para1619{[]int{9, 7, 8, 7, 7, 8, 4, 4, 6, 8, 8, 7, 6, 8, 8, 9, 2, 6, 0, 0, 1, 10, 8, 6, 3, 3, 5, 1, 10, 9, 0, 7, 10, 0, 10, 4, 1, 10, 6, 9, 3, 6, 0, 0, 2, 7, 0, 6, 7, 2, 9, 7, 7, 3, 0, 1, 6, 1, 10, 3}}, ans1619{5.27778}, }, { para1619{[]int{4, 8, 4, 10, 0, 7, 1, 3, 7, 8, 8, 3, 4, 1, 6, 2, 1, 1, 8, 0, 9, 8, 0, 3, 9, 10, 3, 10, 1, 10, 7, 3, 2, 1, 4, 9, 10, 7, 6, 4, 0, 8, 5, 1, 2, 1, 6, 2, 5, 0, 7, 10, 9, 10, 3, 7, 10, 5, 8, 5, 7, 6, 7, 6, 10, 9, 5, 10, 5, 5, 7, 2, 10, 7, 7, 8, 2, 0, 1, 1}}, ans1619{5.29167}, }, } fmt.Printf("------------------------Leetcode Problem 1619------------------------\n") for _, q := range qs { _, p := q.ans1619, q.para1619 fmt.Printf("【input】:%v 【output】:%v \n", p, trimMean(p.p)) } 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/0202.Happy-Number/202. Happy Number.go
leetcode/0202.Happy-Number/202. Happy Number.go
package leetcode func isHappy(n int) bool { record := map[int]int{} for n != 1 { record[n] = n n = getSquareOfDigits(n) for _, previous := range record { if n == previous { return false } } } return true } func getSquareOfDigits(n int) int { squareOfDigits := 0 temporary := n for temporary != 0 { remainder := temporary % 10 squareOfDigits += remainder * remainder temporary /= 10 } return squareOfDigits }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0202.Happy-Number/202. Happy Number_test.go
leetcode/0202.Happy-Number/202. Happy Number_test.go
package leetcode import ( "fmt" "testing" ) type question202 struct { para202 ans202 } // para 是参数 // one 代表第一个参数 type para202 struct { one int } // ans 是答案 // one 代表第一个答案 type ans202 struct { one bool } func Test_Problem202(t *testing.T) { qs := []question202{ { para202{202}, ans202{false}, }, { para202{19}, ans202{true}, }, { para202{2}, ans202{false}, }, { para202{3}, ans202{false}, }, } fmt.Printf("------------------------Leetcode Problem 202------------------------\n") for _, q := range qs { _, p := q.ans202, q.para202 fmt.Printf("【input】:%v 【output】:%v\n", p, isHappy(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/0485.Max-Consecutive-Ones/485. Max Consecutive Ones_test.go
leetcode/0485.Max-Consecutive-Ones/485. Max Consecutive Ones_test.go
package leetcode import ( "fmt" "testing" ) type question485 struct { para485 ans485 } // para 是参数 // one 代表第一个参数 type para485 struct { one []int } // ans 是答案 // one 代表第一个答案 type ans485 struct { one int } func Test_Problem485(t *testing.T) { qs := []question485{ { para485{[]int{1, 1, 0, 1, 1, 1}}, ans485{3}, }, { para485{[]int{1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1}}, ans485{4}, }, // 如需多个测试,可以复制上方元素。 } fmt.Printf("------------------------Leetcode Problem 485------------------------\n") for _, q := range qs { _, p := q.ans485, q.para485 fmt.Printf("【input】:%v 【output】:%v\n", p, findMaxConsecutiveOnes(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/0485.Max-Consecutive-Ones/485. Max Consecutive Ones.go
leetcode/0485.Max-Consecutive-Ones/485. Max Consecutive Ones.go
package leetcode func findMaxConsecutiveOnes(nums []int) int { maxCount, currentCount := 0, 0 for _, v := range nums { if v == 1 { currentCount++ } else { currentCount = 0 } if currentCount > maxCount { maxCount = currentCount } } return maxCount }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0067.Add-Binary/67. Add Binary.go
leetcode/0067.Add-Binary/67. Add Binary.go
package leetcode import ( "strconv" "strings" ) func addBinary(a string, b string) string { if len(b) > len(a) { a, b = b, a } res := make([]string, len(a)+1) i, j, k, c := len(a)-1, len(b)-1, len(a), 0 for i >= 0 && j >= 0 { ai, _ := strconv.Atoi(string(a[i])) bj, _ := strconv.Atoi(string(b[j])) res[k] = strconv.Itoa((ai + bj + c) % 2) c = (ai + bj + c) / 2 i-- j-- k-- } for i >= 0 { ai, _ := strconv.Atoi(string(a[i])) res[k] = strconv.Itoa((ai + c) % 2) c = (ai + c) / 2 i-- k-- } if c > 0 { res[k] = strconv.Itoa(c) } return strings.Join(res, "") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0067.Add-Binary/67. Add Binary_test.go
leetcode/0067.Add-Binary/67. Add Binary_test.go
package leetcode import ( "fmt" "testing" ) type question67 struct { para67 ans67 } // para 是参数 // one 代表第一个参数 type para67 struct { a string b string } // ans 是答案 // one 代表第一个答案 type ans67 struct { one string } func Test_Problem67(t *testing.T) { qs := []question67{ { para67{"11", "1"}, ans67{"100"}, }, { para67{"1010", "1011"}, ans67{"10101"}, }, } fmt.Printf("------------------------Leetcode Problem 67------------------------\n") for _, q := range qs { _, p := q.ans67, q.para67 fmt.Printf("【input】:%v 【output】:%v\n", p, addBinary(p.a, p.b)) } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0575.Distribute-Candies/575. Distribute Candies.go
leetcode/0575.Distribute-Candies/575. Distribute Candies.go
package leetcode func distributeCandies(candies []int) int { n, m := len(candies), make(map[int]struct{}, len(candies)) for _, candy := range candies { m[candy] = struct{}{} } res := len(m) if n/2 < res { return n / 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/0575.Distribute-Candies/575. Distribute Candies_test.go
leetcode/0575.Distribute-Candies/575. Distribute Candies_test.go
package leetcode import ( "fmt" "testing" ) type question575 struct { para575 ans575 } // para 是参数 // one 代表第一个参数 type para575 struct { one []int } // ans 是答案 // one 代表第一个答案 type ans575 struct { one int } func Test_Problem575(t *testing.T) { qs := []question575{ { para575{[]int{1, 1, 2, 2, 3, 3}}, ans575{3}, }, { para575{[]int{1, 1, 2, 3}}, ans575{2}, }, } fmt.Printf("------------------------Leetcode Problem 575------------------------\n") for _, q := range qs { _, p := q.ans575, q.para575 fmt.Printf("【input】:%v 【output】:%v\n", p, distributeCandies(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/0746.Min-Cost-Climbing-Stairs/746. Min Cost Climbing Stairs.go
leetcode/0746.Min-Cost-Climbing-Stairs/746. Min Cost Climbing Stairs.go
package leetcode // 解法一 DP func minCostClimbingStairs(cost []int) int { dp := make([]int, len(cost)) dp[0], dp[1] = cost[0], cost[1] for i := 2; i < len(cost); i++ { dp[i] = cost[i] + min(dp[i-2], dp[i-1]) } return min(dp[len(cost)-2], dp[len(cost)-1]) } func min(a int, b int) int { if a > b { return b } return a } // 解法二 DP 优化辅助空间 func minCostClimbingStairs1(cost []int) int { var cur, last int for i := 2; i < len(cost)+1; i++ { if last+cost[i-1] > cur+cost[i-2] { cur, last = last, cur+cost[i-2] } else { cur, last = last, last+cost[i-1] } } return last }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0746.Min-Cost-Climbing-Stairs/746. Min Cost Climbing Stairs_test.go
leetcode/0746.Min-Cost-Climbing-Stairs/746. Min Cost Climbing Stairs_test.go
package leetcode import ( "fmt" "testing" ) type question746 struct { para746 ans746 } // para 是参数 // one 代表第一个参数 type para746 struct { c []int } // ans 是答案 // one 代表第一个答案 type ans746 struct { one int } func Test_Problem746(t *testing.T) { qs := []question746{ { para746{[]int{10, 15, 20}}, ans746{15}, }, { para746{[]int{1, 100, 1, 1, 1, 100, 1, 1, 100, 1}}, ans746{6}, }, } fmt.Printf("------------------------Leetcode Problem 746------------------------\n") for _, q := range qs { _, p := q.ans746, q.para746 fmt.Printf("【input】:%v 【output】:%v\n", p, minCostClimbingStairs(p.c)) } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0073.Set-Matrix-Zeroes/73. Set Matrix Zeroes.go
leetcode/0073.Set-Matrix-Zeroes/73. Set Matrix Zeroes.go
package leetcode func setZeroes(matrix [][]int) { if len(matrix) == 0 || len(matrix[0]) == 0 { return } isFirstRowExistZero, isFirstColExistZero := false, false for i := 0; i < len(matrix); i++ { if matrix[i][0] == 0 { isFirstColExistZero = true break } } for j := 0; j < len(matrix[0]); j++ { if matrix[0][j] == 0 { isFirstRowExistZero = true break } } for i := 1; i < len(matrix); i++ { for j := 1; j < len(matrix[0]); j++ { if matrix[i][j] == 0 { matrix[i][0] = 0 matrix[0][j] = 0 } } } // 处理[1:]行全部置 0 for i := 1; i < len(matrix); i++ { if matrix[i][0] == 0 { for j := 1; j < len(matrix[0]); j++ { matrix[i][j] = 0 } } } // 处理[1:]列全部置 0 for j := 1; j < len(matrix[0]); j++ { if matrix[0][j] == 0 { for i := 1; i < len(matrix); i++ { matrix[i][j] = 0 } } } if isFirstRowExistZero { for j := 0; j < len(matrix[0]); j++ { matrix[0][j] = 0 } } if isFirstColExistZero { for i := 0; i < len(matrix); i++ { matrix[i][0] = 0 } } }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0073.Set-Matrix-Zeroes/73. Set Matrix Zeroes_test.go
leetcode/0073.Set-Matrix-Zeroes/73. Set Matrix Zeroes_test.go
package leetcode import ( "fmt" "testing" ) type question73 struct { para73 ans73 } // para 是参数 // one 代表第一个参数 type para73 struct { matrix [][]int } // ans 是答案 // one 代表第一个答案 type ans73 struct { } func Test_Problem73(t *testing.T) { qs := []question73{ { para73{[][]int{ {0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}, }}, ans73{}, }, } fmt.Printf("------------------------Leetcode Problem 73------------------------\n") for _, q := range qs { _, p := q.ans73, q.para73 fmt.Printf("【input】:%v ", p) setZeroes(p.matrix) fmt.Printf("【output】:%v\n", p) } 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/0786.K-th-Smallest-Prime-Fraction/786. K-th Smallest Prime Fraction_test.go
leetcode/0786.K-th-Smallest-Prime-Fraction/786. K-th Smallest Prime Fraction_test.go
package leetcode import ( "fmt" "testing" ) type question786 struct { para786 ans786 } // para 是参数 // one 代表第一个参数 type para786 struct { A []int K int } // ans 是答案 // one 代表第一个答案 type ans786 struct { one []int } func Test_Problem786(t *testing.T) { qs := []question786{ { para786{[]int{1, 2, 3, 5}, 3}, ans786{[]int{2, 5}}, }, { para786{[]int{1, 7}, 1}, ans786{[]int{1, 7}}, }, { para786{[]int{1, 2}, 1}, ans786{[]int{1, 2}}, }, { para786{[]int{1, 2, 3, 5, 7}, 6}, ans786{[]int{3, 7}}, }, } fmt.Printf("------------------------Leetcode Problem 786------------------------\n") for _, q := range qs { _, p := q.ans786, q.para786 fmt.Printf("【input】:%v 【output】:%v\n", p, kthSmallestPrimeFraction(p.A, 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/0786.K-th-Smallest-Prime-Fraction/786. K-th Smallest Prime Fraction.go
leetcode/0786.K-th-Smallest-Prime-Fraction/786. K-th Smallest Prime Fraction.go
package leetcode import ( "sort" ) // 解法一 二分搜索 func kthSmallestPrimeFraction(A []int, K int) []int { low, high, n := 0.0, 1.0, len(A) // 因为是在小数内使用二分查找,无法像在整数范围内那样通过 mid+1 和边界判断来终止循环 // 所以此处根据 count 来结束循环 for { mid, count, p, q, j := (high+low)/2.0, 0, 0, 1, 0 for i := 0; i < n; i++ { for j < n && float64(A[i]) > float64(mid)*float64(A[j]) { j++ } count += n - j if j < n && q*A[i] > p*A[j] { p = A[i] q = A[j] } } if count == K { return []int{p, q} } else if count < K { low = mid } else { high = mid } } } // 解法二 暴力解法,时间复杂度 O(n^2) func kthSmallestPrimeFraction1(A []int, K int) []int { if len(A) == 0 || (len(A)*(len(A)-1))/2 < K { return []int{} } fractions := []Fraction{} for i := 0; i < len(A); i++ { for j := i + 1; j < len(A); j++ { fractions = append(fractions, Fraction{molecule: A[i], denominator: A[j]}) } } sort.Sort(SortByFraction(fractions)) return []int{fractions[K-1].molecule, fractions[K-1].denominator} } // Fraction define type Fraction struct { molecule int denominator int } // SortByFraction define type SortByFraction []Fraction func (a SortByFraction) Len() int { return len(a) } func (a SortByFraction) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a SortByFraction) Less(i, j int) bool { return a[i].molecule*a[j].denominator < a[j].molecule*a[i].denominator }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0488.Zuma-Game/488.Zuma Game_test.go
leetcode/0488.Zuma-Game/488.Zuma Game_test.go
package leetcode import ( "fmt" "testing" ) type question488 struct { para488 ans488 } // para 是参数 type para488 struct { board string hand string } // ans 是答案 type ans488 struct { ans int } func Test_Problem488(t *testing.T) { qs := []question488{ { para488{"WRRBBW", "RB"}, ans488{-1}, }, { para488{"WWRRBBWW", "WRBRW"}, ans488{2}, }, { para488{"G", "GGGGG"}, ans488{2}, }, { para488{"RBYYBBRRB", "YRBGB"}, ans488{3}, }, } fmt.Printf("------------------------Leetcode Problem 488------------------------\n") for _, q := range qs { _, p := q.ans488, q.para488 fmt.Printf("【input】:%v 【output】:%v\n", p, findMinStep(p.board, p.hand)) } 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/0488.Zuma-Game/488.Zuma Game.go
leetcode/0488.Zuma-Game/488.Zuma Game.go
package leetcode func findMinStep(board string, hand string) int { q := [][]string{{board, hand}} mp := make(map[string]bool) minStep := 0 for len(q) > 0 { length := len(q) minStep++ for length > 0 { length-- cur := q[0] q = q[1:] curB, curH := cur[0], cur[1] for i := 0; i < len(curB); i++ { for j := 0; j < len(curH); j++ { curB2 := del3(curB[0:i] + string(curH[j]) + curB[i:]) curH2 := curH[0:j] + curH[j+1:] if len(curB2) == 0 { return minStep } if _, ok := mp[curB2+curH2]; ok { continue } mp[curB2+curH2] = true q = append(q, []string{curB2, curH2}) } } } } return -1 } func del3(str string) string { cnt := 1 for i := 1; i < len(str); i++ { if str[i] == str[i-1] { cnt++ } else { if cnt >= 3 { return del3(str[0:i-cnt] + str[i:]) } cnt = 1 } } if cnt >= 3 { return str[0 : len(str)-cnt] } return str }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0397.Integer-Replacement/397. Integer Replacement.go
leetcode/0397.Integer-Replacement/397. Integer Replacement.go
package leetcode func integerReplacement(n int) int { res := 0 for n > 1 { if (n & 1) == 0 { // 判断是否是偶数 n >>= 1 } else if (n+1)%4 == 0 && n != 3 { // 末尾 2 位为 11 n++ } else { // 末尾 2 位为 01 n-- } 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/0397.Integer-Replacement/397. Integer Replacement_test.go
leetcode/0397.Integer-Replacement/397. Integer Replacement_test.go
package leetcode import ( "fmt" "testing" ) type question397 struct { para397 ans397 } // para 是参数 // one 代表第一个参数 type para397 struct { s int } // ans 是答案 // one 代表第一个答案 type ans397 struct { one int } func Test_Problem397(t *testing.T) { qs := []question397{ { para397{8}, ans397{3}, }, { para397{7}, ans397{4}, }, } fmt.Printf("------------------------Leetcode Problem 397------------------------\n") for _, q := range qs { _, p := q.ans397, q.para397 fmt.Printf("【input】:%v 【output】:%v\n", p, integerReplacement(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/9990316.Remove-Duplicate-Letters/316. Remove Duplicate Letters_test.go
leetcode/9990316.Remove-Duplicate-Letters/316. Remove Duplicate Letters_test.go
package leetcode import ( "fmt" "testing" ) type question316 struct { para316 ans316 } // para 是参数 // one 代表第一个参数 type para316 struct { one string } // ans 是答案 // one 代表第一个答案 type ans316 struct { one string } func Test_Problem316(t *testing.T) { qs := []question316{ { para316{"bcabc"}, ans316{"abc"}, }, { para316{"cbacdcbc"}, ans316{"acdb"}, }, } fmt.Printf("------------------------Leetcode Problem 316------------------------\n") for _, q := range qs { _, p := q.ans316, q.para316 fmt.Printf("【input】:%v 【output】:%v\n", p, removeDuplicateLetters(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/9990316.Remove-Duplicate-Letters/316. Remove Duplicate Letters.go
leetcode/9990316.Remove-Duplicate-Letters/316. Remove Duplicate Letters.go
package leetcode func removeDuplicateLetters(s string) string { return "" }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0141.Linked-List-Cycle/141. Linked List Cycle_test.go
leetcode/0141.Linked-List-Cycle/141. Linked List Cycle_test.go
package leetcode import ( "fmt" "testing" "github.com/halfrost/LeetCode-Go/structures" ) type question141 struct { para141 ans141 } // para 是参数 // one 代表第一个参数 type para141 struct { one []int } // ans 是答案 // one 代表第一个答案 type ans141 struct { one bool } func Test_Problem141(t *testing.T) { qs := []question141{ { para141{[]int{3, 2, 0, -4}}, ans141{false}, }, { para141{[]int{1, 2}}, ans141{false}, }, { para141{[]int{1}}, ans141{false}, }, } fmt.Printf("------------------------Leetcode Problem 141------------------------\n") for _, q := range qs { _, p := q.ans141, q.para141 fmt.Printf("【input】:%v 【output】:%v\n", p, hasCycle(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/0141.Linked-List-Cycle/141. Linked List Cycle.go
leetcode/0141.Linked-List-Cycle/141. Linked List Cycle.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 hasCycle(head *ListNode) bool { fast := head slow := head for fast != nil && fast.Next != nil { fast = fast.Next.Next slow = slow.Next if fast == slow { 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/0969.Pancake-Sorting/969. Pancake Sorting.go
leetcode/0969.Pancake-Sorting/969. Pancake Sorting.go
package leetcode func pancakeSort(A []int) []int { if len(A) == 0 { return []int{} } right := len(A) var ( ans []int ) for right > 0 { idx := find(A, right) if idx != right-1 { reverse969(A, 0, idx) reverse969(A, 0, right-1) ans = append(ans, idx+1, right) } right-- } return ans } func reverse969(nums []int, l, r int) { for l < r { nums[l], nums[r] = nums[r], nums[l] l++ r-- } } func find(nums []int, t int) int { for i, num := range nums { if num == t { return i } } return -1 }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0969.Pancake-Sorting/969. Pancake Sorting_test.go
leetcode/0969.Pancake-Sorting/969. Pancake Sorting_test.go
package leetcode import ( "fmt" "testing" ) type question969 struct { para969 ans969 } // para 是参数 // one 代表第一个参数 type para969 struct { one []int } // ans 是答案 // one 代表第一个答案 type ans969 struct { one []int } func Test_Problem969(t *testing.T) { qs := []question969{ { para969{[]int{}}, ans969{[]int{}}, }, { para969{[]int{1}}, ans969{[]int{1}}, }, { para969{[]int{3, 2, 4, 1}}, ans969{[]int{3, 4, 2, 3, 1, 2}}, }, } fmt.Printf("------------------------Leetcode Problem 969------------------------\n") for _, q := range qs { _, p := q.ans969, q.para969 fmt.Printf("【input】:%v 【output】:%v\n", p, pancakeSort(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/0095.Unique-Binary-Search-Trees-II/95. Unique Binary Search Trees II_test.go
leetcode/0095.Unique-Binary-Search-Trees-II/95. Unique Binary Search Trees II_test.go
package leetcode import ( "fmt" "testing" "github.com/halfrost/LeetCode-Go/structures" ) type question95 struct { para95 ans95 } // para 是参数 // one 代表第一个参数 type para95 struct { one int } // ans 是答案 // one 代表第一个答案 type ans95 struct { one []*TreeNode } func Test_Problem95(t *testing.T) { qs := []question95{ { para95{1}, ans95{[]*TreeNode{{Val: 1, Left: nil, Right: nil}}}, }, { para95{3}, ans95{[]*TreeNode{ {Val: 1, Left: nil, Right: &TreeNode{Val: 3, Left: &TreeNode{Val: 2, Left: nil, Right: nil}, Right: nil}}, {Val: 1, Left: nil, Right: &TreeNode{Val: 2, Left: nil, Right: &TreeNode{Val: 3, Left: nil, Right: nil}}}, {Val: 3, Left: &TreeNode{Val: 2, Left: &TreeNode{Val: 1, Left: nil, Right: nil}, Right: nil}, Right: nil}, {Val: 3, Left: &TreeNode{Val: 1, Left: nil, Right: &TreeNode{Val: 2, Left: nil, Right: nil}}, Right: nil}, {Val: 2, Left: &TreeNode{Val: 1, Left: nil, Right: nil}, Right: &TreeNode{Val: 3, Left: nil, Right: nil}}, }}}, } fmt.Printf("------------------------Leetcode Problem 95------------------------\n") for _, q := range qs { _, p := q.ans95, q.para95 fmt.Printf("【input】:%v \n", p) trees := generateTrees(p.one) for _, t := range trees { fmt.Printf("【output】:%v\n", structures.Tree2Preorder(t)) } } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0095.Unique-Binary-Search-Trees-II/95. Unique Binary Search Trees II.go
leetcode/0095.Unique-Binary-Search-Trees-II/95. Unique Binary Search Trees II.go
package leetcode import ( "github.com/halfrost/LeetCode-Go/structures" ) // TreeNode define type TreeNode = structures.TreeNode /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func generateTrees(n int) []*TreeNode { if n == 0 { return []*TreeNode{} } return generateBSTree(1, n) } func generateBSTree(start, end int) []*TreeNode { tree := []*TreeNode{} if start > end { tree = append(tree, nil) return tree } for i := start; i <= end; i++ { left := generateBSTree(start, i-1) right := generateBSTree(i+1, end) for _, l := range left { for _, r := range right { root := &TreeNode{Val: i, Left: l, Right: r} tree = append(tree, root) } } } return tree }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0142.Linked-List-Cycle-II/142. Linked List Cycle II_test.go
leetcode/0142.Linked-List-Cycle-II/142. Linked List Cycle II_test.go
package leetcode import "testing" func Test_Problem142(t *testing.T) { }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0142.Linked-List-Cycle-II/142. Linked List Cycle II.go
leetcode/0142.Linked-List-Cycle-II/142. Linked List Cycle II.go
package leetcode import ( "github.com/halfrost/LeetCode-Go/structures" ) // ListNode define type ListNode = structures.ListNode /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func detectCycle(head *ListNode) *ListNode { if head == nil || head.Next == nil { return nil } isCycle, slow := hasCycle142(head) if !isCycle { return nil } fast := head for fast != slow { fast = fast.Next slow = slow.Next } return fast } func hasCycle142(head *ListNode) (bool, *ListNode) { fast := head slow := head for slow != nil && fast != nil && fast.Next != nil { fast = fast.Next.Next slow = slow.Next if fast == slow { return true, slow } } return false, nil }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1396.Design-Underground-System/1396. Design Underground System_test.go
leetcode/1396.Design-Underground-System/1396. Design Underground System_test.go
package leetcode import ( "fmt" "testing" ) func Test_Problem(t *testing.T) { undergroundSystem := Constructor() undergroundSystem.CheckIn(45, "Leyton", 3) undergroundSystem.CheckIn(32, "Paradise", 8) undergroundSystem.CheckIn(27, "Leyton", 10) undergroundSystem.CheckOut(45, "Waterloo", 15) undergroundSystem.CheckOut(27, "Waterloo", 20) undergroundSystem.CheckOut(32, "Cambridge", 22) fmt.Println("Output: ", undergroundSystem.GetAverageTime("Paradise", "Cambridge")) // return 14.00000. There was only one travel from "Paradise" (at time 8) to "Cambridge" (at time 22) fmt.Println("Output: ", undergroundSystem.GetAverageTime("Leyton", "Waterloo")) // return 11.00000. There were two travels from "Leyton" to "Waterloo", a customer with id=45 from time=3 to time=15 and a customer with id=27 from time=10 to time=20. So the average time is ( (15-3) + (20-10) ) / 2 = 11.00000 undergroundSystem.CheckIn(10, "Leyton", 24) fmt.Println("Output: ", undergroundSystem.GetAverageTime("Leyton", "Waterloo")) // return 11.00000 undergroundSystem.CheckOut(10, "Waterloo", 38) fmt.Println("Output: ", undergroundSystem.GetAverageTime("Leyton", "Waterloo")) // return 12.00000 undergroundSystem.CheckIn(10, "Leyton", 3) undergroundSystem.CheckOut(10, "Paradise", 8) fmt.Println("Output: ", undergroundSystem.GetAverageTime("Leyton", "Paradise")) // return 5.00000 undergroundSystem.CheckIn(5, "Leyton", 10) undergroundSystem.CheckOut(5, "Paradise", 16) fmt.Println("Output: ", undergroundSystem.GetAverageTime("Leyton", "Paradise")) // return 5.50000 undergroundSystem.CheckIn(2, "Leyton", 21) undergroundSystem.CheckOut(2, "Paradise", 30) fmt.Println("Output: ", undergroundSystem.GetAverageTime("Leyton", "Paradise")) // return 6.66667 }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1396.Design-Underground-System/1396. Design Underground System.go
leetcode/1396.Design-Underground-System/1396. Design Underground System.go
package leetcode type checkin struct { station string time int } type stationTime struct { sum, count float64 } type UndergroundSystem struct { checkins map[int]*checkin stationTimes map[string]map[string]*stationTime } func Constructor() UndergroundSystem { return UndergroundSystem{ make(map[int]*checkin), make(map[string]map[string]*stationTime), } } func (s *UndergroundSystem) CheckIn(id int, stationName string, t int) { s.checkins[id] = &checkin{stationName, t} } func (s *UndergroundSystem) CheckOut(id int, stationName string, t int) { checkin := s.checkins[id] destination := s.stationTimes[checkin.station] if destination == nil { s.stationTimes[checkin.station] = make(map[string]*stationTime) } st := s.stationTimes[checkin.station][stationName] if st == nil { st = new(stationTime) s.stationTimes[checkin.station][stationName] = st } st.sum += float64(t - checkin.time) st.count++ delete(s.checkins, id) } func (s *UndergroundSystem) GetAverageTime(startStation string, endStation string) float64 { st := s.stationTimes[startStation][endStation] return st.sum / st.count } /** * Your UndergroundSystem object will be instantiated and called as such: * obj := Constructor(); * obj.CheckIn(id,stationName,t); * obj.CheckOut(id,stationName,t); * param_3 := obj.GetAverageTime(startStation,endStation); */
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1203.Sort-Items-by-Groups-Respecting-Dependencies/1203. Sort Items by Groups Respecting Dependencies_test.go
leetcode/1203.Sort-Items-by-Groups-Respecting-Dependencies/1203. Sort Items by Groups Respecting Dependencies_test.go
package leetcode import ( "fmt" "testing" ) type question1203 struct { para1203 ans1203 } // para 是参数 // one 代表第一个参数 type para1203 struct { n int m int group []int beforeItems [][]int } // ans 是答案 // one 代表第一个答案 type ans1203 struct { one []int } func Test_Problem1203(t *testing.T) { qs := []question1203{ { para1203{8, 2, []int{-1, -1, 1, 0, 0, 1, 0, -1}, [][]int{{}, {6}, {5}, {6}, {3, 6}, {}, {}, {}}}, ans1203{[]int{6, 3, 4, 5, 2, 0, 7, 1}}, }, { para1203{8, 2, []int{-1, -1, 1, 0, 0, 1, 0, -1}, [][]int{{}, {6}, {5}, {6}, {3}, {}, {4}, {}}}, ans1203{[]int{}}, }, } fmt.Printf("------------------------Leetcode Problem 1203------------------------\n") for _, q := range qs { _, p := q.ans1203, q.para1203 fmt.Printf("【input】:%v 【output】:%v\n", p, sortItems1(p.n, p.m, p.group, p.beforeItems)) } 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/1203.Sort-Items-by-Groups-Respecting-Dependencies/1203. Sort Items by Groups Respecting Dependencies.go
leetcode/1203.Sort-Items-by-Groups-Respecting-Dependencies/1203. Sort Items by Groups Respecting Dependencies.go
package leetcode // 解法一 拓扑排序版的 DFS func sortItems(n int, m int, group []int, beforeItems [][]int) []int { groups, inDegrees := make([][]int, n+m), make([]int, n+m) for i, g := range group { if g > -1 { g += n groups[g] = append(groups[g], i) inDegrees[i]++ } } for i, ancestors := range beforeItems { gi := group[i] if gi == -1 { gi = i } else { gi += n } for _, ancestor := range ancestors { ga := group[ancestor] if ga == -1 { ga = ancestor } else { ga += n } if gi == ga { groups[ancestor] = append(groups[ancestor], i) inDegrees[i]++ } else { groups[ga] = append(groups[ga], gi) inDegrees[gi]++ } } } res := []int{} for i, d := range inDegrees { if d == 0 { sortItemsDFS(i, n, &res, &inDegrees, &groups) } } if len(res) != n { return nil } return res } func sortItemsDFS(i, n int, res, inDegrees *[]int, groups *[][]int) { if i < n { *res = append(*res, i) } (*inDegrees)[i] = -1 for _, ch := range (*groups)[i] { if (*inDegrees)[ch]--; (*inDegrees)[ch] == 0 { sortItemsDFS(ch, n, res, inDegrees, groups) } } } // 解法二 二维拓扑排序 时间复杂度 O(m+n),空间复杂度 O(m+n) func sortItems1(n int, m int, group []int, beforeItems [][]int) []int { groupItems, res := map[int][]int{}, []int{} for i := 0; i < len(group); i++ { if group[i] == -1 { group[i] = m + i } groupItems[group[i]] = append(groupItems[group[i]], i) } groupGraph, groupDegree, itemGraph, itemDegree := make([][]int, m+n), make([]int, m+n), make([][]int, n), make([]int, n) for i := 0; i < len(beforeItems); i++ { for j := 0; j < len(beforeItems[i]); j++ { if group[beforeItems[i][j]] != group[i] { // 不同组项目,确定组间依赖关系 groupGraph[group[beforeItems[i][j]]] = append(groupGraph[group[beforeItems[i][j]]], group[i]) groupDegree[group[i]]++ } else { // 同组项目,确定组内依赖关系 itemGraph[beforeItems[i][j]] = append(itemGraph[beforeItems[i][j]], i) itemDegree[i]++ } } } items := []int{} for i := 0; i < m+n; i++ { items = append(items, i) } // 组间拓扑 groupOrders := topSort(groupGraph, groupDegree, items) if len(groupOrders) < len(items) { return nil } for i := 0; i < len(groupOrders); i++ { items := groupItems[groupOrders[i]] // 组内拓扑 orders := topSort(itemGraph, itemDegree, items) if len(orders) < len(items) { return nil } res = append(res, orders...) } return res } func topSort(graph [][]int, deg, items []int) (orders []int) { q := []int{} for _, i := range items { if deg[i] == 0 { q = append(q, i) } } for len(q) > 0 { from := q[0] q = q[1:] orders = append(orders, from) for _, to := range graph[from] { deg[to]-- if deg[to] == 0 { q = append(q, to) } } } return }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0374.Guess-Number-Higher-or-Lower/374. Guess Number Higher or Lower.go
leetcode/0374.Guess-Number-Higher-or-Lower/374. Guess Number Higher or Lower.go
package leetcode import "sort" /** * Forward declaration of guess API. * @param num your guess * @return -1 if num is lower than the guess number * 1 if num is higher than the guess number * otherwise return 0 * func guess(num int) int; */ func guessNumber(n int) int { return sort.Search(n, func(x int) bool { return guess(x) <= 0 }) } func guess(num int) int { return 0 }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0374.Guess-Number-Higher-or-Lower/374. Guess Number Higher or Lower_test.go
leetcode/0374.Guess-Number-Higher-or-Lower/374. Guess Number Higher or Lower_test.go
package leetcode import ( "fmt" "testing" ) type question374 struct { para374 ans374 } // para 是参数 // one 代表第一个参数 type para374 struct { n int } // ans 是答案 // one 代表第一个答案 type ans374 struct { one int } func Test_Problem374(t *testing.T) { qs := []question374{ { para374{10}, ans374{6}, }, { para374{1}, ans374{1}, }, { para374{2}, ans374{1}, }, { para374{2}, ans374{2}, }, // 如需多个测试,可以复制上方元素。 } fmt.Printf("------------------------Leetcode Problem 374------------------------\n") for _, q := range qs { _, p := q.ans374, q.para374 fmt.Printf("【input】:%v 【output】:%v\n", p, guessNumber(p.n)) } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0911.Online-Election/911. Online Election_test.go
leetcode/0911.Online-Election/911. Online Election_test.go
package leetcode import ( "fmt" "testing" ) func Test_Problem911(t *testing.T) { obj := Constructor911([]int{0, 1, 1, 0, 0, 1, 0}, []int{0, 5, 10, 15, 20, 25, 30}) fmt.Printf("obj.Q[3] = %v\n", obj.Q(3)) // 0 fmt.Printf("obj.Q[12] = %v\n", obj.Q(12)) // 1 fmt.Printf("obj.Q[25] = %v\n", obj.Q(25)) // 1 fmt.Printf("obj.Q[15] = %v\n", obj.Q(15)) // 0 fmt.Printf("obj.Q[24] = %v\n", obj.Q(24)) // 0 fmt.Printf("obj.Q[8] = %v\n", obj.Q(8)) // 1 obj = Constructor911([]int{0, 0, 0, 0, 1}, []int{0, 6, 39, 52, 75}) fmt.Printf("obj.Q[45] = %v\n", obj.Q(45)) // 0 fmt.Printf("obj.Q[49] = %v\n", obj.Q(49)) // 0 fmt.Printf("obj.Q[59] = %v\n", obj.Q(59)) // 0 fmt.Printf("obj.Q[68] = %v\n", obj.Q(68)) // 0 fmt.Printf("obj.Q[42] = %v\n", obj.Q(42)) // 0 fmt.Printf("obj.Q[37] = %v\n", obj.Q(37)) // 0 fmt.Printf("obj.Q[99] = %v\n", obj.Q(99)) // 0 fmt.Printf("obj.Q[26] = %v\n", obj.Q(26)) // 0 fmt.Printf("obj.Q[78] = %v\n", obj.Q(78)) // 0 fmt.Printf("obj.Q[43] = %v\n", obj.Q(43)) // 0 }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0911.Online-Election/911. Online Election.go
leetcode/0911.Online-Election/911. Online Election.go
package leetcode import ( "sort" ) // TopVotedCandidate define type TopVotedCandidate struct { persons []int times []int } // Constructor911 define func Constructor911(persons []int, times []int) TopVotedCandidate { leaders, votes := make([]int, len(persons)), make([]int, len(persons)) leader := persons[0] for i := 0; i < len(persons); i++ { p := persons[i] votes[p]++ if votes[p] >= votes[leader] { leader = p } leaders[i] = leader } return TopVotedCandidate{persons: leaders, times: times} } // Q define func (tvc *TopVotedCandidate) Q(t int) int { i := sort.Search(len(tvc.times), func(p int) bool { return tvc.times[p] > t }) return tvc.persons[i-1] } /** * Your TopVotedCandidate object will be instantiated and called as such: * obj := Constructor(persons, times); * param_1 := obj.Q(t); */
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1463.Cherry-Pickup-II/1463. Cherry Pickup II_test.go
leetcode/1463.Cherry-Pickup-II/1463. Cherry Pickup II_test.go
package leetcode import ( "fmt" "testing" ) type question1463 struct { para1463 ans1463 } type para1463 struct { grid [][]int } type ans1463 struct { ans int } func Test_Problem1463(t *testing.T) { qs := []question1463{ { para1463{[][]int{ {3, 1, 1}, {2, 5, 1}, {1, 5, 5}, {2, 1, 1}, }}, ans1463{24}, }, { para1463{[][]int{ {1, 0, 0, 0, 0, 0, 1}, {2, 0, 0, 0, 0, 3, 0}, {2, 0, 9, 0, 0, 0, 0}, {0, 3, 0, 5, 4, 0, 0}, {1, 0, 2, 3, 0, 0, 6}, }}, ans1463{28}, }, { para1463{[][]int{ {1, 0, 0, 3}, {0, 0, 0, 3}, {0, 0, 3, 3}, {9, 0, 3, 3}, }}, ans1463{22}, }, { para1463{[][]int{ {1, 1}, {1, 1}, }}, ans1463{4}, }, } fmt.Printf("------------------------Leetcode Problem 1463------------------------\n") for _, q := range qs { _, p := q.ans1463, q.para1463 fmt.Printf("【input】:%v ", p) fmt.Printf("【output】:%v \n", cherryPickup(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/1463.Cherry-Pickup-II/1463. Cherry Pickup II.go
leetcode/1463.Cherry-Pickup-II/1463. Cherry Pickup II.go
package leetcode func cherryPickup(grid [][]int) int { rows, cols := len(grid), len(grid[0]) dp := make([][][]int, rows) for i := 0; i < rows; i++ { dp[i] = make([][]int, cols) for j := 0; j < cols; j++ { dp[i][j] = make([]int, cols) } } for i := 0; i < rows; i++ { for j := 0; j <= i && j < cols; j++ { for k := cols - 1; k >= cols-1-i && k >= 0; k-- { max := 0 for a := j - 1; a <= j+1; a++ { for b := k - 1; b <= k+1; b++ { sum := isInBoard(dp, i-1, a, b) if a == b && i > 0 && a >= 0 && a < cols { sum -= grid[i-1][a] } if sum > max { max = sum } } } if j == k { max += grid[i][j] } else { max += grid[i][j] + grid[i][k] } dp[i][j][k] = max } } } count := 0 for j := 0; j < cols && j < rows; j++ { for k := cols - 1; k >= 0 && k >= cols-rows; k-- { if dp[rows-1][j][k] > count { count = dp[rows-1][j][k] } } } return count } func isInBoard(dp [][][]int, i, j, k int) int { if i < 0 || j < 0 || j >= len(dp[0]) || k < 0 || k >= len(dp[0]) { return 0 } return dp[i][j][k] }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0378.Kth-Smallest-Element-in-a-Sorted-Matrix/378. Kth Smallest Element in a Sorted Matrix.go
leetcode/0378.Kth-Smallest-Element-in-a-Sorted-Matrix/378. Kth Smallest Element in a Sorted Matrix.go
package leetcode import ( "container/heap" ) // 解法一 二分搜索 func kthSmallest378(matrix [][]int, k int) int { m, n, low := len(matrix), len(matrix[0]), matrix[0][0] high := matrix[m-1][n-1] + 1 for low < high { mid := low + (high-low)>>1 // 如果 count 比 k 小,在大值的那一半继续二分搜索 if counterKthSmall(m, n, mid, matrix) >= k { high = mid } else { low = mid + 1 } } return low } func counterKthSmall(m, n, mid int, matrix [][]int) int { count, j := 0, n-1 // 每次循环统计比 mid 值小的元素个数 for i := 0; i < m; i++ { // 遍历每行中比 mid 小的元素的个数 for j >= 0 && mid < matrix[i][j] { j-- } count += j + 1 } return count } // 解法二 优先队列 func kthSmallest3781(matrix [][]int, k int) int { if len(matrix) == 0 || len(matrix[0]) == 0 { return 0 } pq := &pq{data: make([]interface{}, k)} heap.Init(pq) for i := 0; i < len(matrix); i++ { for j := 0; j < len(matrix[0]); j++ { if pq.Len() < k { heap.Push(pq, matrix[i][j]) } else if matrix[i][j] < pq.Head().(int) { heap.Pop(pq) heap.Push(pq, matrix[i][j]) } else { break } } } return heap.Pop(pq).(int) } type pq struct { data []interface{} len int } func (p *pq) Len() int { return p.len } func (p *pq) Less(a, b int) bool { return p.data[a].(int) > p.data[b].(int) } func (p *pq) Swap(a, b int) { p.data[a], p.data[b] = p.data[b], p.data[a] } func (p *pq) Push(o interface{}) { p.data[p.len] = o p.len++ } func (p *pq) Head() interface{} { return p.data[0] } func (p *pq) Pop() interface{} { p.len-- return p.data[p.len] }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0378.Kth-Smallest-Element-in-a-Sorted-Matrix/378. Kth Smallest Element in a Sorted Matrix_test.go
leetcode/0378.Kth-Smallest-Element-in-a-Sorted-Matrix/378. Kth Smallest Element in a Sorted Matrix_test.go
package leetcode import ( "fmt" "testing" ) type question378 struct { para378 ans378 } // para 是参数 // one 代表第一个参数 type para378 struct { matrix [][]int k int } // ans 是答案 // one 代表第一个答案 type ans378 struct { one int } func Test_Problem378(t *testing.T) { qs := []question378{ { para378{[][]int{{1, 5, 9}, {10, 11, 13}, {12, 13, 15}}, 8}, ans378{13}, }, { para378{[][]int{{1, 5, 7}, {11, 12, 13}, {12, 13, 15}}, 3}, ans378{9}, }, } fmt.Printf("------------------------Leetcode Problem 378------------------------\n") for _, q := range qs { _, p := q.ans378, q.para378 fmt.Printf("【input】:%v 【output】:%v\n", p, kthSmallest378(p.matrix, 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/0980.Unique-Paths-III/980. Unique Paths III.go
leetcode/0980.Unique-Paths-III/980. Unique Paths III.go
package leetcode var dir = [][]int{ {-1, 0}, {0, 1}, {1, 0}, {0, -1}, } func uniquePathsIII(grid [][]int) int { visited := make([][]bool, len(grid)) for i := 0; i < len(visited); i++ { visited[i] = make([]bool, len(grid[0])) } res, empty, startx, starty, endx, endy, path := 0, 0, 0, 0, 0, 0, []int{} for i, v := range grid { for j, vv := range v { switch vv { case 0: empty++ case 1: startx, starty = i, j case 2: endx, endy = i, j } } } findUniquePathIII(grid, visited, path, empty+1, startx, starty, endx, endy, &res) // 可走的步数要加一,因为终点格子也算一步,不然永远走不到终点! return res } func isInPath(board [][]int, x, y int) bool { return x >= 0 && x < len(board) && y >= 0 && y < len(board[0]) } func findUniquePathIII(board [][]int, visited [][]bool, path []int, empty, startx, starty, endx, endy int, res *int) { if startx == endx && starty == endy { if empty == 0 { *res++ } return } if board[startx][starty] >= 0 { visited[startx][starty] = true empty-- path = append(path, startx) path = append(path, starty) for i := 0; i < 4; i++ { nx := startx + dir[i][0] ny := starty + dir[i][1] if isInPath(board, nx, ny) && !visited[nx][ny] { findUniquePathIII(board, visited, path, empty, nx, ny, endx, endy, res) } } visited[startx][starty] = false //empty++ 这里虽然可以还原这个变量值,但是赋值没有意义,干脆不写了 path = path[:len(path)-2] } return }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0980.Unique-Paths-III/980. Unique Paths III_test.go
leetcode/0980.Unique-Paths-III/980. Unique Paths III_test.go
package leetcode import ( "fmt" "testing" ) type question980 struct { para980 ans980 } // para 是参数 // one 代表第一个参数 type para980 struct { grid [][]int } // ans 是答案 // one 代表第一个答案 type ans980 struct { one int } func Test_Problem980(t *testing.T) { qs := []question980{ { para980{[][]int{ {1, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 2, -1}, }}, ans980{2}, }, { para980{[][]int{ {1, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 2}, }}, ans980{4}, }, { para980{[][]int{ {1, 0}, {0, 2}, }}, ans980{0}, }, } fmt.Printf("------------------------Leetcode Problem 980------------------------\n") for _, q := range qs { _, p := q.ans980, q.para980 fmt.Printf("【input】:%v 【output】:%v\n\n\n", p, uniquePathsIII(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/0811.Subdomain-Visit-Count/811. Subdomain Visit Count_test.go
leetcode/0811.Subdomain-Visit-Count/811. Subdomain Visit Count_test.go
package leetcode import ( "fmt" "testing" ) type question811 struct { para811 ans811 } // para 是参数 // one 代表第一个参数 type para811 struct { one []string } // ans 是答案 // one 代表第一个答案 type ans811 struct { one []string } func Test_Problem811(t *testing.T) { qs := []question811{ { para811{[]string{"9001 discuss.leetcode.com"}}, ans811{[]string{"mqe", "mqE", "mQe", "mQE", "Mqe", "MqE", "MQe", "MQE"}}, }, { para811{[]string{"900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"}}, ans811{[]string{"901 mail.com", "50 yahoo.com", "900 google.mail.com", "5 wiki.org", "5 org", "1 intel.mail.com", "951 com"}}, }, } fmt.Printf("------------------------Leetcode Problem 811------------------------\n") for _, q := range qs { _, p := q.ans811, q.para811 fmt.Printf("【input】:%v 【output】:%v\n", p, subdomainVisits(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/0811.Subdomain-Visit-Count/811. Subdomain Visit Count.go
leetcode/0811.Subdomain-Visit-Count/811. Subdomain Visit Count.go
package leetcode import ( "strconv" "strings" ) // 解法一 func subdomainVisits(cpdomains []string) []string { result := make([]string, 0) if len(cpdomains) == 0 { return result } domainCountMap := make(map[string]int, 0) for _, domain := range cpdomains { countDomain := strings.Split(domain, " ") allDomains := strings.Split(countDomain[1], ".") temp := make([]string, 0) for i := len(allDomains) - 1; i >= 0; i-- { temp = append([]string{allDomains[i]}, temp...) ld := strings.Join(temp, ".") count, _ := strconv.Atoi(countDomain[0]) if val, ok := domainCountMap[ld]; !ok { domainCountMap[ld] = count } else { domainCountMap[ld] = count + val } } } for k, v := range domainCountMap { t := strings.Join([]string{strconv.Itoa(v), k}, " ") result = append(result, t) } return result } // 解法二 func subdomainVisits1(cpdomains []string) []string { out := make([]string, 0) var b strings.Builder domains := make(map[string]int, 0) for _, v := range cpdomains { splitDomain(v, domains) } for k, v := range domains { b.WriteString(strconv.Itoa(v)) b.WriteString(" ") b.WriteString(k) out = append(out, b.String()) b.Reset() } return out } func splitDomain(domain string, domains map[string]int) { visits := 0 var e error subdomains := make([]string, 0) for i, v := range domain { if v == ' ' { visits, e = strconv.Atoi(domain[0:i]) if e != nil { panic(e) } break } } for i := len(domain) - 1; i >= 0; i-- { if domain[i] == '.' { subdomains = append(subdomains, domain[i+1:]) } else if domain[i] == ' ' { subdomains = append(subdomains, domain[i+1:]) break } } for _, v := range subdomains { count, ok := domains[v] if ok { domains[v] = count + visits } else { domains[v] = visits } } }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0376.Wiggle-Subsequence/376. Wiggle Subsequence_test.go
leetcode/0376.Wiggle-Subsequence/376. Wiggle Subsequence_test.go
package leetcode import ( "fmt" "testing" ) type question376 struct { para376 ans376 } // para 是参数 // one 代表第一个参数 type para376 struct { nums []int } // ans 是答案 // one 代表第一个答案 type ans376 struct { one int } func Test_Problem376(t *testing.T) { qs := []question376{ { para376{[]int{1, 7, 4, 9, 2, 5}}, ans376{6}, }, { para376{[]int{1, 17, 5, 10, 13, 15, 10, 5, 16, 8}}, ans376{7}, }, { para376{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9}}, ans376{2}, }, } fmt.Printf("------------------------Leetcode Problem 376------------------------\n") for _, q := range qs { _, p := q.ans376, q.para376 fmt.Printf("【input】:%v 【output】:%v\n", p, wiggleMaxLength(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/0376.Wiggle-Subsequence/376. Wiggle Subsequence.go
leetcode/0376.Wiggle-Subsequence/376. Wiggle Subsequence.go
package leetcode func wiggleMaxLength(nums []int) int { if len(nums) < 2 { return len(nums) } res := 1 prevDiff := nums[1] - nums[0] if prevDiff != 0 { res = 2 } for i := 2; i < len(nums); i++ { diff := nums[i] - nums[i-1] if diff > 0 && prevDiff <= 0 || diff < 0 && prevDiff >= 0 { res++ prevDiff = diff } } return res }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0057.Insert-Interval/57. Insert Interval.go
leetcode/0057.Insert-Interval/57. Insert Interval.go
package leetcode import ( "github.com/halfrost/LeetCode-Go/structures" ) // Interval define type Interval = structures.Interval /** * Definition for an interval. * type Interval struct { * Start int * End int * } */ func insert(intervals []Interval, newInterval Interval) []Interval { res := make([]Interval, 0) if len(intervals) == 0 { res = append(res, newInterval) return res } curIndex := 0 for curIndex < len(intervals) && intervals[curIndex].End < newInterval.Start { res = append(res, intervals[curIndex]) curIndex++ } for curIndex < len(intervals) && intervals[curIndex].Start <= newInterval.End { newInterval = Interval{Start: min(newInterval.Start, intervals[curIndex].Start), End: max(newInterval.End, intervals[curIndex].End)} curIndex++ } res = append(res, newInterval) for curIndex < len(intervals) { res = append(res, intervals[curIndex]) curIndex++ } return res } func max(a int, b int) int { if a > b { return a } return b } func min(a int, b int) int { if a > b { return b } return a }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0057.Insert-Interval/57. Insert Interval_test.go
leetcode/0057.Insert-Interval/57. Insert Interval_test.go
package leetcode import ( "fmt" "testing" ) type question57 struct { para57 ans57 } // para 是参数 // one 代表第一个参数 type para57 struct { one []Interval two Interval } // ans 是答案 // one 代表第一个答案 type ans57 struct { one []Interval } func Test_Problem57(t *testing.T) { qs := []question57{ { para57{[]Interval{}, Interval{}}, ans57{[]Interval{}}, }, { para57{[]Interval{{Start: 1, End: 3}, {Start: 6, End: 9}}, Interval{Start: 4, End: 8}}, ans57{[]Interval{{Start: 1, End: 5}, {Start: 6, End: 9}}}, }, { para57{[]Interval{{Start: 1, End: 3}, {Start: 6, End: 9}}, Interval{Start: 2, End: 5}}, ans57{[]Interval{{Start: 1, End: 5}, {Start: 6, End: 9}}}, }, { para57{[]Interval{{Start: 1, End: 2}, {Start: 3, End: 5}, {Start: 6, End: 7}, {Start: 8, End: 10}, {Start: 12, End: 16}}, Interval{Start: 4, End: 8}}, ans57{[]Interval{{Start: 1, End: 2}, {Start: 3, End: 10}, {Start: 12, End: 16}}}, }, { para57{[]Interval{{Start: 1, End: 5}}, Interval{Start: 5, End: 7}}, ans57{[]Interval{{Start: 1, End: 7}}}, }, { para57{[]Interval{{Start: 1, End: 2}, {Start: 3, End: 5}, {Start: 6, End: 7}, {Start: 8, End: 10}, {Start: 12, End: 16}}, Interval{Start: 9, End: 12}}, ans57{[]Interval{{Start: 1, End: 2}, {Start: 3, End: 5}, {Start: 6, End: 7}, {Start: 8, End: 16}}}, }, } fmt.Printf("------------------------Leetcode Problem 57------------------------\n") for _, q := range qs { _, p := q.ans57, q.para57 fmt.Printf("【input】:%v 【output】:%v\n", p, insert(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/0745.Prefix-and-Suffix-Search/745. Prefix and Suffix Search.go
leetcode/0745.Prefix-and-Suffix-Search/745. Prefix and Suffix Search.go
package leetcode import "strings" // 解法一 查找时间复杂度 O(1) type WordFilter struct { words map[string]int } func Constructor745(words []string) WordFilter { wordsMap := make(map[string]int, len(words)*5) for k := 0; k < len(words); k++ { for i := 0; i <= 10 && i <= len(words[k]); i++ { for j := len(words[k]); 0 <= j && len(words[k])-10 <= j; j-- { ps := words[k][:i] + "#" + words[k][j:] wordsMap[ps] = k } } } return WordFilter{words: wordsMap} } func (this *WordFilter) F(prefix string, suffix string) int { ps := prefix + "#" + suffix if index, ok := this.words[ps]; ok { return index } return -1 } // 解法二 查找时间复杂度 O(N * L) type WordFilter_ struct { input []string } func Constructor_745_(words []string) WordFilter_ { return WordFilter_{input: words} } func (this *WordFilter_) F_(prefix string, suffix string) int { for i := len(this.input) - 1; i >= 0; i-- { if strings.HasPrefix(this.input[i], prefix) && strings.HasSuffix(this.input[i], suffix) { return i } } return -1 } /** * Your WordFilter object will be instantiated and called as such: * obj := Constructor(words); * param_1 := obj.F(prefix,suffix); */
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0745.Prefix-and-Suffix-Search/745. Prefix and Suffix Search_test.go
leetcode/0745.Prefix-and-Suffix-Search/745. Prefix and Suffix Search_test.go
package leetcode import ( "fmt" "testing" ) func Test_Problem745(t *testing.T) { obj := Constructor745([]string{"apple"}) fmt.Printf("obj = %v\n", obj) param1 := obj.F("a", "e") fmt.Printf("param_1 = %v obj = %v\n", param1, obj) param2 := obj.F("b", "") fmt.Printf("param_2 = %v obj = %v\n", param2, obj) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1143.Longest-Common-Subsequence/1143. Longest Common Subsequence_test.go
leetcode/1143.Longest-Common-Subsequence/1143. Longest Common Subsequence_test.go
package leetcode import ( "fmt" "testing" ) type question1143 struct { para1143 ans1143 } // para 是参数 // one 代表第一个参数 type para1143 struct { text1 string text2 string } // ans 是答案 // one 代表第一个答案 type ans1143 struct { one int } func Test_Problem1143(t *testing.T) { qs := []question1143{ { para1143{"abcde", "ace"}, ans1143{3}, }, { para1143{"abc", "abc"}, ans1143{3}, }, { para1143{"abc", "def"}, ans1143{0}, }, } fmt.Printf("------------------------Leetcode Problem 1143------------------------\n") for _, q := range qs { _, p := q.ans1143, q.para1143 fmt.Printf("【input】:%v 【output】:%v\n", p, longestCommonSubsequence(p.text1, p.text2)) } 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/1143.Longest-Common-Subsequence/1143. Longest Common Subsequence.go
leetcode/1143.Longest-Common-Subsequence/1143. Longest Common Subsequence.go
package leetcode func longestCommonSubsequence(text1 string, text2 string) int { if len(text1) == 0 || len(text2) == 0 { return 0 } dp := make([][]int, len(text1)+1) for i := range dp { dp[i] = make([]int, len(text2)+1) } for i := 1; i < len(text1)+1; i++ { for j := 1; j < len(text2)+1; j++ { if text1[i-1] == text2[j-1] { dp[i][j] = dp[i-1][j-1] + 1 } else { dp[i][j] = max(dp[i][j-1], dp[i-1][j]) } } } return dp[len(text1)][len(text2)] } func max(a, b int) int { if a > b { return a } return b }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0685.Redundant-Connection-II/685. Redundant Connection II_test.go
leetcode/0685.Redundant-Connection-II/685. Redundant Connection II_test.go
package leetcode import ( "fmt" "testing" ) type question685 struct { para685 ans685 } // para 是参数 // one 代表第一个参数 type para685 struct { one [][]int } // ans 是答案 // one 代表第一个答案 type ans685 struct { one []int } func Test_Problem685(t *testing.T) { qs := []question685{ { para685{[][]int{{3, 5}, {1, 3}, {2, 1}, {5, 4}, {2, 3}}}, ans685{[]int{2, 3}}, }, { para685{[][]int{{4, 2}, {1, 5}, {5, 2}, {5, 3}, {2, 4}}}, ans685{[]int{4, 2}}, }, { para685{[][]int{{1, 2}, {1, 3}, {2, 3}}}, ans685{[]int{2, 3}}, }, { para685{[][]int{{1, 2}, {2, 3}, {3, 4}, {1, 4}, {1, 5}}}, ans685{[]int{1, 4}}, }, { para685{[][]int{{2, 1}, {3, 1}, {4, 2}, {1, 4}}}, ans685{[]int{2, 1}}, }, } fmt.Printf("------------------------Leetcode Problem 685------------------------\n") for _, q := range qs { _, p := q.ans685, q.para685 fmt.Printf("【input】:%v 【output】:%v\n", p, findRedundantDirectedConnection(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/0685.Redundant-Connection-II/685. Redundant Connection II.go
leetcode/0685.Redundant-Connection-II/685. Redundant Connection II.go
package leetcode func findRedundantDirectedConnection(edges [][]int) []int { if len(edges) == 0 { return []int{} } parent, candidate1, candidate2 := make([]int, len(edges)+1), []int{}, []int{} for _, edge := range edges { if parent[edge[1]] == 0 { parent[edge[1]] = edge[0] } else { // 如果一个节点已经有父亲节点了,说明入度已经有 1 了,再来一条边,入度为 2 ,那么跳过新来的这条边 candidate2,并记录下和这条边冲突的边 candidate1 candidate1 = append(candidate1, parent[edge[1]]) candidate1 = append(candidate1, edge[1]) candidate2 = append(candidate2, edge[0]) candidate2 = append(candidate2, edge[1]) edge[1] = 0 // 做标记,后面再扫到这条边以后可以直接跳过 } } for i := 1; i <= len(edges); i++ { parent[i] = i } for _, edge := range edges { if edge[1] == 0 { // 跳过 candidate2 这条边 continue } u, v := edge[0], edge[1] pu := findRoot(&parent, u) if pu == v { // 发现有环 if len(candidate1) == 0 { // 如果没有出现入度为 2 的情况,那么对应情况 1,就删除这条边 return edge } return candidate1 // 出现环并且有入度为 2 的情况,说明 candidate1 是答案 } parent[v] = pu // 没有发现环,继续合并 } return candidate2 // 当最后什么都没有发生,则 candidate2 是答案 } func findRoot(parent *[]int, k int) int { if (*parent)[k] != k { (*parent)[k] = findRoot(parent, (*parent)[k]) } return (*parent)[k] }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1659.Maximize-Grid-Happiness/1659. Maximize Grid Happiness.go
leetcode/1659.Maximize-Grid-Happiness/1659. Maximize Grid Happiness.go
package leetcode import ( "math" ) func getMaxGridHappiness(m int, n int, introvertsCount int, extrovertsCount int) int { // lineStatus 将每一行中 3 种状态进行编码,空白 - 0,内向人 - 1,外向人 - 2,每行状态用三进制表示 // lineStatusList[729][6] 每一行的三进制表示 // introvertsCountInner[729] 每一个 lineStatus 包含的内向人数 // extrovertsCountInner[729] 每一个 lineStatus 包含的外向人数 // scoreInner[729] 每一个 lineStatus 包含的行内得分(只统计 lineStatus 本身的得分,不包括它与上一行的) // scoreOuter[729][729] 每一个 lineStatus 包含的行外得分 // dp[上一行的 lineStatus][当前处理到的行][剩余的内向人数][剩余的外向人数] n3, lineStatus, introvertsCountInner, extrovertsCountInner, scoreInner, scoreOuter, lineStatusList, dp := math.Pow(3.0, float64(n)), 0, [729]int{}, [729]int{}, [729]int{}, [729][729]int{}, [729][6]int{}, [729][6][7][7]int{} for i := 0; i < 729; i++ { lineStatusList[i] = [6]int{} } for i := 0; i < 729; i++ { dp[i] = [6][7][7]int{} for j := 0; j < 6; j++ { dp[i][j] = [7][7]int{} for k := 0; k < 7; k++ { dp[i][j][k] = [7]int{-1, -1, -1, -1, -1, -1, -1} } } } // 预处理 for lineStatus = 0; lineStatus < int(n3); lineStatus++ { tmp := lineStatus for i := 0; i < n; i++ { lineStatusList[lineStatus][i] = tmp % 3 tmp /= 3 } introvertsCountInner[lineStatus], extrovertsCountInner[lineStatus], scoreInner[lineStatus] = 0, 0, 0 for i := 0; i < n; i++ { if lineStatusList[lineStatus][i] != 0 { // 个人分数 if lineStatusList[lineStatus][i] == 1 { introvertsCountInner[lineStatus]++ scoreInner[lineStatus] += 120 } else if lineStatusList[lineStatus][i] == 2 { extrovertsCountInner[lineStatus]++ scoreInner[lineStatus] += 40 } // 行内分数 if i-1 >= 0 { scoreInner[lineStatus] += closeScore(lineStatusList[lineStatus][i], lineStatusList[lineStatus][i-1]) } } } } // 行外分数 for lineStatus0 := 0; lineStatus0 < int(n3); lineStatus0++ { for lineStatus1 := 0; lineStatus1 < int(n3); lineStatus1++ { scoreOuter[lineStatus0][lineStatus1] = 0 for i := 0; i < n; i++ { scoreOuter[lineStatus0][lineStatus1] += closeScore(lineStatusList[lineStatus0][i], lineStatusList[lineStatus1][i]) } } } return dfs(0, 0, introvertsCount, extrovertsCount, m, int(n3), &dp, &introvertsCountInner, &extrovertsCountInner, &scoreInner, &scoreOuter) } // 如果 x 和 y 相邻,需要加上的分数 func closeScore(x, y int) int { if x == 0 || y == 0 { return 0 } // 两个内向的人,每个人要 -30,一共 -60 if x == 1 && y == 1 { return -60 } if x == 2 && y == 2 { return 40 } return -10 } // dfs(上一行的 lineStatus,当前处理到的行,剩余的内向人数,剩余的外向人数) func dfs(lineStatusLast, row, introvertsCount, extrovertsCount, m, n3 int, dp *[729][6][7][7]int, introvertsCountInner, extrovertsCountInner, scoreInner *[729]int, scoreOuter *[729][729]int) int { // 边界条件:如果已经处理完,或者没有人了 if row == m || introvertsCount+extrovertsCount == 0 { return 0 } // 记忆化 if dp[lineStatusLast][row][introvertsCount][extrovertsCount] != -1 { return dp[lineStatusLast][row][introvertsCount][extrovertsCount] } best := 0 for lineStatus := 0; lineStatus < n3; lineStatus++ { if introvertsCountInner[lineStatus] > introvertsCount || extrovertsCountInner[lineStatus] > extrovertsCount { continue } score := scoreInner[lineStatus] + scoreOuter[lineStatus][lineStatusLast] best = max(best, score+dfs(lineStatus, row+1, introvertsCount-introvertsCountInner[lineStatus], extrovertsCount-extrovertsCountInner[lineStatus], m, n3, dp, introvertsCountInner, extrovertsCountInner, scoreInner, scoreOuter)) } dp[lineStatusLast][row][introvertsCount][extrovertsCount] = best return best } 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/1659.Maximize-Grid-Happiness/1659. Maximize Grid Happiness_test.go
leetcode/1659.Maximize-Grid-Happiness/1659. Maximize Grid Happiness_test.go
package leetcode import ( "fmt" "testing" ) type question1659 struct { para1659 ans1659 } // para 是参数 // one 代表第一个参数 type para1659 struct { m int n int introvertsCount int extrovertsCount int } // ans 是答案 // one 代表第一个答案 type ans1659 struct { one int } func Test_Problem1659(t *testing.T) { qs := []question1659{ { para1659{2, 3, 1, 2}, ans1659{240}, }, { para1659{3, 1, 2, 1}, ans1659{260}, }, { para1659{2, 2, 4, 0}, ans1659{240}, }, } fmt.Printf("------------------------Leetcode Problem 1659------------------------\n") for _, q := range qs { _, p := q.ans1659, q.para1659 fmt.Printf("【input】:%v 【output】:%v \n", p, getMaxGridHappiness(p.m, p.n, p.introvertsCount, p.extrovertsCount)) } 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/0726.Number-of-Atoms/726. Number of Atoms.go
leetcode/0726.Number-of-Atoms/726. Number of Atoms.go
package leetcode import ( "sort" "strconv" "strings" ) type atom struct { name string cnt int } type atoms []atom func (this atoms) Len() int { return len(this) } func (this atoms) Less(i, j int) bool { return strings.Compare(this[i].name, this[j].name) < 0 } func (this atoms) Swap(i, j int) { this[i], this[j] = this[j], this[i] } func (this atoms) String() string { s := "" for _, a := range this { s += a.name if a.cnt > 1 { s += strconv.Itoa(a.cnt) } } return s } func countOfAtoms(s string) string { n := len(s) if n == 0 { return "" } stack := make([]string, 0) for i := 0; i < n; i++ { c := s[i] if c == '(' || c == ')' { stack = append(stack, string(c)) } else if isUpperLetter(c) { j := i + 1 for ; j < n; j++ { if !isLowerLetter(s[j]) { break } } stack = append(stack, s[i:j]) i = j - 1 } else if isDigital(c) { j := i + 1 for ; j < n; j++ { if !isDigital(s[j]) { break } } stack = append(stack, s[i:j]) i = j - 1 } } cnt, deep := make([]map[string]int, 100), 0 for i := 0; i < 100; i++ { cnt[i] = make(map[string]int) } for i := 0; i < len(stack); i++ { t := stack[i] if isUpperLetter(t[0]) { num := 1 if i+1 < len(stack) && isDigital(stack[i+1][0]) { num, _ = strconv.Atoi(stack[i+1]) i++ } cnt[deep][t] += num } else if t == "(" { deep++ } else if t == ")" { num := 1 if i+1 < len(stack) && isDigital(stack[i+1][0]) { num, _ = strconv.Atoi(stack[i+1]) i++ } for k, v := range cnt[deep] { cnt[deep-1][k] += v * num } cnt[deep] = make(map[string]int) deep-- } } as := atoms{} for k, v := range cnt[0] { as = append(as, atom{name: k, cnt: v}) } sort.Sort(as) return as.String() } func isDigital(v byte) bool { if v >= '0' && v <= '9' { return true } return false } func isUpperLetter(v byte) bool { if v >= 'A' && v <= 'Z' { return true } return false } func isLowerLetter(v byte) bool { if v >= 'a' && v <= 'z' { 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/0726.Number-of-Atoms/726. Number of Atoms_test.go
leetcode/0726.Number-of-Atoms/726. Number of Atoms_test.go
package leetcode import ( "fmt" "testing" ) type question726 struct { para726 ans726 } // para 是参数 // one 代表第一个参数 type para726 struct { one string } // ans 是答案 // one 代表第一个答案 type ans726 struct { one string } func Test_Problem726(t *testing.T) { qs := []question726{ { para726{"H200P"}, ans726{"H200P"}, }, { para726{"H2O"}, ans726{"H2O"}, }, { para726{"Mg(OH)2"}, ans726{"H2MgO2"}, }, { para726{"K4(ON(SO3)2)2"}, ans726{"K4N2O14S4"}, }, } fmt.Printf("------------------------Leetcode Problem 726------------------------\n") for _, q := range qs { _, p := q.ans726, q.para726 fmt.Printf("【input】:%v 【output】:%v\n", p, countOfAtoms(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/0031.Next-Permutation/31. Next Permutation_test.go
leetcode/0031.Next-Permutation/31. Next Permutation_test.go
package leetcode import ( "fmt" "testing" ) type question31 struct { para31 ans31 } // para 是参数 // one 代表第一个参数 type para31 struct { nums []int } // ans 是答案 // one 代表第一个答案 type ans31 struct { one []int } func Test_Problem31(t *testing.T) { qs := []question31{ { para31{[]int{1, 2, 3}}, ans31{[]int{1, 3, 2}}, }, { para31{[]int{3, 2, 1}}, ans31{[]int{1, 2, 3}}, }, { para31{[]int{1, 1, 5}}, ans31{[]int{1, 5, 1}}, }, { para31{[]int{1}}, ans31{[]int{1}}, }, } fmt.Printf("------------------------Leetcode Problem 31------------------------\n") for _, q := range qs { _, p := q.ans31, q.para31 fmt.Printf("【input】:%v ", p) nextPermutation(p.nums) fmt.Printf("【output】:%v\n", p.nums) } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0031.Next-Permutation/31. Next Permutation.go
leetcode/0031.Next-Permutation/31. Next Permutation.go
package leetcode // 解法一 func nextPermutation(nums []int) { i, j := 0, 0 for i = len(nums) - 2; i >= 0; i-- { if nums[i] < nums[i+1] { break } } if i >= 0 { for j = len(nums) - 1; j > i; j-- { if nums[j] > nums[i] { break } } swap(&nums, i, j) } reverse(&nums, i+1, len(nums)-1) } func reverse(nums *[]int, i, j int) { for i < j { swap(nums, i, j) i++ j-- } } func swap(nums *[]int, i, j int) { (*nums)[i], (*nums)[j] = (*nums)[j], (*nums)[i] } // 解法二 // [2,(3),6,5,4,1] -> 2,(4),6,5,(3),1 -> 2,4, 1,3,5,6 func nextPermutation1(nums []int) { var n = len(nums) var pIdx = checkPermutationPossibility(nums) if pIdx == -1 { reverse(&nums, 0, n-1) return } var rp = len(nums) - 1 // start from right most to leftward,find the first number which is larger than PIVOT for rp > 0 { if nums[rp] > nums[pIdx] { swap(&nums, pIdx, rp) break } else { rp-- } } // Finally, Reverse all elements which are right from pivot reverse(&nums, pIdx+1, n-1) } // checkPermutationPossibility returns 1st occurrence Index where // value is in decreasing order(from right to left) // returns -1 if not found(it's already in its last permutation) func checkPermutationPossibility(nums []int) (idx int) { // search right to left for 1st number(from right) that is not in increasing order var rp = len(nums) - 1 for rp > 0 { if nums[rp-1] < nums[rp] { idx = rp - 1 return idx } rp-- } return -1 }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0985.Sum-of-Even-Numbers-After-Queries/985. Sum of Even Numbers After Queries_test.go
leetcode/0985.Sum-of-Even-Numbers-After-Queries/985. Sum of Even Numbers After Queries_test.go
package leetcode import ( "fmt" "testing" ) type question985 struct { para985 ans985 } // para 是参数 // one 代表第一个参数 type para985 struct { A []int queries [][]int } // ans 是答案 // one 代表第一个答案 type ans985 struct { one []int } func Test_Problem985(t *testing.T) { qs := []question985{ { para985{[]int{1, 2, 3, 4}, [][]int{{1, 0}, {-3, 1}, {-4, 0}, {2, 3}}}, ans985{[]int{8, 6, 2, 4}}, }, } fmt.Printf("------------------------Leetcode Problem 985------------------------\n") for _, q := range qs { _, p := q.ans985, q.para985 fmt.Printf("【input】:%v 【output】:%v\n\n\n", p, sumEvenAfterQueries(p.A, p.queries)) } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0985.Sum-of-Even-Numbers-After-Queries/985. Sum of Even Numbers After Queries.go
leetcode/0985.Sum-of-Even-Numbers-After-Queries/985. Sum of Even Numbers After Queries.go
package leetcode func sumEvenAfterQueries(A []int, queries [][]int) []int { cur, res := 0, []int{} for _, v := range A { if v%2 == 0 { cur += v } } for _, q := range queries { if A[q[1]]%2 == 0 { cur -= A[q[1]] } A[q[1]] += q[0] if A[q[1]]%2 == 0 { cur += A[q[1]] } res = append(res, cur) } return res }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0216.Combination-Sum-III/216. Combination Sum III_test.go
leetcode/0216.Combination-Sum-III/216. Combination Sum III_test.go
package leetcode import ( "fmt" "testing" ) type question216 struct { para216 ans216 } // para 是参数 // one 代表第一个参数 type para216 struct { n int k int } // ans 是答案 // one 代表第一个答案 type ans216 struct { one [][]int } func Test_Problem216(t *testing.T) { qs := []question216{ { para216{3, 7}, ans216{[][]int{{1, 2, 4}}}, }, { para216{3, 9}, ans216{[][]int{{1, 2, 6}, {1, 3, 5}, {2, 3, 4}}}, }, } fmt.Printf("------------------------Leetcode Problem 216------------------------\n") for _, q := range qs { _, p := q.ans216, q.para216 fmt.Printf("【input】:%v 【output】:%v\n", p, combinationSum3(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/0216.Combination-Sum-III/216. Combination Sum III.go
leetcode/0216.Combination-Sum-III/216. Combination Sum III.go
package leetcode func combinationSum3(k int, n int) [][]int { if k == 0 { return [][]int{} } c, res := []int{}, [][]int{} findcombinationSum3(k, n, 1, c, &res) return res } func findcombinationSum3(k, target, index int, c []int, res *[][]int) { if target == 0 { if len(c) == k { b := make([]int, len(c)) copy(b, c) *res = append(*res, b) } return } for i := index; i < 10; i++ { if target >= i { c = append(c, i) findcombinationSum3(k, target-i, i+1, c, res) c = c[:len(c)-1] } } }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0167.Two-Sum-II-Input-array-is-sorted/167. Two Sum II - Input array is sorted.go
leetcode/0167.Two-Sum-II-Input-array-is-sorted/167. Two Sum II - Input array is sorted.go
package leetcode // 解法一 这一题可以利用数组有序的特性 func twoSum167(numbers []int, target int) []int { i, j := 0, len(numbers)-1 for i < j { if numbers[i]+numbers[j] == target { return []int{i + 1, j + 1} } if numbers[i]+numbers[j] < target { i++ } else { j-- } } return nil } // 解法二 不管数组是否有序,空间复杂度比上一种解法要多 O(n) func twoSum167_1(numbers []int, target int) []int { m := make(map[int]int) for i := 0; i < len(numbers); i++ { another := target - numbers[i] if idx, ok := m[another]; ok { return []int{idx + 1, i + 1} } m[numbers[i]] = i } return nil }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0167.Two-Sum-II-Input-array-is-sorted/167. Two Sum II - Input array is sorted_test.go
leetcode/0167.Two-Sum-II-Input-array-is-sorted/167. Two Sum II - Input array is sorted_test.go
package leetcode import ( "fmt" "testing" ) type question167 struct { para167 ans167 } // para 是参数 // one 代表第一个参数 type para167 struct { one []int two int } // ans 是答案 // one 代表第一个答案 type ans167 struct { one []int } func Test_Problem167(t *testing.T) { qs := []question167{ { para167{[]int{2, 7, 11, 15}, 9}, ans167{[]int{1, 2}}, }, } fmt.Printf("------------------------Leetcode Problem 167------------------------\n") for _, q := range qs { _, p := q.ans167, q.para167 fmt.Printf("【input】:%v 【output】:%v\n", p.one, twoSum167(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/0045.Jump-Game-II/45. Jump Game II_test.go
leetcode/0045.Jump-Game-II/45. Jump Game II_test.go
package leetcode import ( "fmt" "testing" ) type question45 struct { para45 ans45 } // para 是参数 // one 代表第一个参数 type para45 struct { nums []int } // ans 是答案 // one 代表第一个答案 type ans45 struct { one int } func Test_Problem45(t *testing.T) { qs := []question45{ { para45{[]int{2, 3, 1, 1, 4}}, ans45{2}, }, { para45{[]int{2, 3, 0, 1, 4}}, ans45{2}, }, } fmt.Printf("------------------------Leetcode Problem 45------------------------\n") for _, q := range qs { _, p := q.ans45, q.para45 fmt.Printf("【input】:%v 【output】:%v\n", p, jump(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/0045.Jump-Game-II/45. Jump Game II.go
leetcode/0045.Jump-Game-II/45. Jump Game II.go
package leetcode func jump(nums []int) int { if len(nums) == 1 { return 0 } needChoose, canReach, step := 0, 0, 0 for i, x := range nums { if i+x > canReach { canReach = i + x if canReach >= len(nums)-1 { return step + 1 } } if i == needChoose { needChoose = canReach step++ } } return step }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0921.Minimum-Add-to-Make-Parentheses-Valid/921. Minimum Add to Make Parentheses Valid.go
leetcode/0921.Minimum-Add-to-Make-Parentheses-Valid/921. Minimum Add to Make Parentheses Valid.go
package leetcode func minAddToMakeValid(S string) int { if len(S) == 0 { return 0 } stack := make([]rune, 0) for _, v := range S { if v == '(' { stack = append(stack, v) } else if (v == ')') && len(stack) > 0 && stack[len(stack)-1] == '(' { stack = stack[:len(stack)-1] } else { stack = append(stack, v) } } return len(stack) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0921.Minimum-Add-to-Make-Parentheses-Valid/921. Minimum Add to Make Parentheses Valid_test.go
leetcode/0921.Minimum-Add-to-Make-Parentheses-Valid/921. Minimum Add to Make Parentheses Valid_test.go
package leetcode import ( "fmt" "testing" ) type question921 struct { para921 ans921 } // para 是参数 // one 代表第一个参数 type para921 struct { one string } // ans 是答案 // one 代表第一个答案 type ans921 struct { one int } func Test_Problem921(t *testing.T) { qs := []question921{ { para921{"())"}, ans921{1}, }, { para921{"((("}, ans921{3}, }, { para921{"()"}, ans921{0}, }, { para921{"()))(("}, ans921{4}, }, } fmt.Printf("------------------------Leetcode Problem 921------------------------\n") for _, q := range qs { _, p := q.ans921, q.para921 fmt.Printf("【input】:%v 【output】:%v\n", p, minAddToMakeValid(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/0436.Find-Right-Interval/436. Find Right Interval.go
leetcode/0436.Find-Right-Interval/436. Find Right Interval.go
package leetcode import ( "sort" "github.com/halfrost/LeetCode-Go/structures" ) // Interval define type Interval = structures.Interval // 解法一 利用系统函数 sort + 二分搜索 func findRightInterval(intervals [][]int) []int { intervalList := make(intervalList, len(intervals)) // 转换成 interval 类型 for i, v := range intervals { intervalList[i] = interval{interval: v, index: i} } sort.Sort(intervalList) out := make([]int, len(intervalList)) for i := 0; i < len(intervalList); i++ { index := sort.Search(len(intervalList), func(p int) bool { return intervalList[p].interval[0] >= intervalList[i].interval[1] }) if index == len(intervalList) { out[intervalList[i].index] = -1 } else { out[intervalList[i].index] = intervalList[index].index } } return out } type interval struct { interval []int index int } type intervalList []interval func (in intervalList) Len() int { return len(in) } func (in intervalList) Less(i, j int) bool { return in[i].interval[0] <= in[j].interval[0] } func (in intervalList) Swap(i, j int) { in[i], in[j] = in[j], in[i] } // 解法二 手撸 sort + 二分搜索 func findRightInterval1(intervals [][]int) []int { if len(intervals) == 0 { return []int{} } intervalsList, res, intervalMap := []Interval{}, []int{}, map[Interval]int{} for k, v := range intervals { intervalsList = append(intervalsList, Interval{Start: v[0], End: v[1]}) intervalMap[Interval{Start: v[0], End: v[1]}] = k } structures.QuickSort(intervalsList, 0, len(intervalsList)-1) for _, v := range intervals { tmp := searchFirstGreaterInterval(intervalsList, v[1]) if tmp > 0 { tmp = intervalMap[intervalsList[tmp]] } res = append(res, tmp) } return res } func searchFirstGreaterInterval(nums []Interval, target int) int { low, high := 0, len(nums)-1 for low <= high { mid := low + ((high - low) >> 1) if nums[mid].Start >= target { if (mid == 0) || (nums[mid-1].Start < target) { // 找到第一个大于等于 target 的元素 return mid } 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/0436.Find-Right-Interval/436. Find Right Interval_test.go
leetcode/0436.Find-Right-Interval/436. Find Right Interval_test.go
package leetcode import ( "fmt" "testing" ) type question436 struct { para436 ans436 } // para 是参数 // one 代表第一个参数 type para436 struct { one [][]int } // ans 是答案 // one 代表第一个答案 type ans436 struct { one []int } func Test_Problem436(t *testing.T) { qs := []question436{ { para436{[][]int{{3, 4}, {2, 3}, {1, 2}}}, ans436{[]int{-1, 0, 1}}, }, { para436{[][]int{{1, 4}, {2, 3}, {3, 4}}}, ans436{[]int{-1, 2, -1}}, }, { para436{[][]int{{1, 2}}}, ans436{[]int{-1}}, }, } fmt.Printf("------------------------Leetcode Problem 436------------------------\n") for _, q := range qs { _, p := q.ans436, q.para436 fmt.Printf("【input】:%v 【output】:%v\n", p, findRightInterval(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/0989.Add-to-Array-Form-of-Integer/989. Add to Array-Form of Integer.go
leetcode/0989.Add-to-Array-Form-of-Integer/989. Add to Array-Form of Integer.go
package leetcode func addToArrayForm(A []int, K int) []int { res := []int{} for i := len(A) - 1; i >= 0; i-- { sum := A[i] + K%10 K /= 10 if sum >= 10 { K++ sum -= 10 } res = append(res, sum) } for ; K > 0; K /= 10 { res = append(res, K%10) } reverse(res) return res } func reverse(A []int) { for i, n := 0, len(A); i < n/2; i++ { A[i], A[n-1-i] = A[n-1-i], A[i] } }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0989.Add-to-Array-Form-of-Integer/989. Add to Array-Form of Integer_test.go
leetcode/0989.Add-to-Array-Form-of-Integer/989. Add to Array-Form of Integer_test.go
package leetcode import ( "fmt" "testing" ) type question989 struct { para989 ans989 } // para 是参数 // one 代表第一个参数 type para989 struct { A []int K int } // ans 是答案 // one 代表第一个答案 type ans989 struct { one []int } func Test_Problem989(t *testing.T) { qs := []question989{ { para989{[]int{1, 2, 0, 0}, 34}, ans989{[]int{1, 2, 3, 4}}, }, { para989{[]int{2, 7, 4}, 181}, ans989{[]int{4, 5, 5}}, }, { para989{[]int{2, 1, 5}, 806}, ans989{[]int{1, 0, 2, 1}}, }, { para989{[]int{9, 9, 9, 9, 9, 9, 9, 9, 9, 9}, 1}, ans989{[]int{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, }, } fmt.Printf("------------------------Leetcode Problem 989------------------------\n") for _, q := range qs { _, p := q.ans989, q.para989 fmt.Printf("【input】:%v 【output】:%v\n", p, addToArrayForm(p.A, 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/0850.Rectangle-Area-II/850. Rectangle Area II_test.go
leetcode/0850.Rectangle-Area-II/850. Rectangle Area II_test.go
package leetcode import ( "fmt" "testing" ) type question850 struct { para850 ans850 } // para 是参数 // one 代表第一个参数 type para850 struct { one [][]int } // ans 是答案 // one 代表第一个答案 type ans850 struct { one int } func Test_Problem850(t *testing.T) { qs := []question850{ { para850{[][]int{{0, 0, 3, 3}, {2, 0, 5, 3}, {1, 1, 4, 4}}}, ans850{18}, }, { para850{[][]int{{0, 0, 1, 1}, {2, 2, 3, 3}}}, ans850{2}, }, { para850{[][]int{{0, 0, 2, 2}, {1, 0, 2, 3}, {1, 0, 3, 1}}}, ans850{6}, }, { para850{[][]int{{0, 0, 1000000000, 1000000000}}}, ans850{49}, }, } fmt.Printf("------------------------Leetcode Problem 850------------------------\n") for _, q := range qs { _, p := q.ans850, q.para850 fmt.Printf("【input】:%v 【output】:%v\n", p, rectangleArea(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/0850.Rectangle-Area-II/850. Rectangle Area II.go
leetcode/0850.Rectangle-Area-II/850. Rectangle Area II.go
package leetcode import ( "sort" ) func rectangleArea(rectangles [][]int) int { sat, res := SegmentAreaTree{}, 0 posXMap, posX, posYMap, posY, lines := discretization850(rectangles) tmp := make([]int, len(posYMap)) for i := 0; i < len(tmp)-1; i++ { tmp[i] = posY[i+1] - posY[i] } sat.Init(tmp, func(i, j int) int { return i + j }) for i := 0; i < len(posY)-1; i++ { tmp[i] = posY[i+1] - posY[i] } for i := 0; i < len(posX)-1; i++ { for _, v := range lines[posXMap[posX[i]]] { sat.Update(posYMap[v.start], posYMap[v.end], v.state) } res += ((posX[i+1] - posX[i]) * sat.Query(0, len(posY)-1)) % 1000000007 } return res % 1000000007 } func discretization850(positions [][]int) (map[int]int, []int, map[int]int, []int, map[int][]LineItem) { tmpXMap, tmpYMap, posXArray, posXMap, posYArray, posYMap, lines := map[int]int{}, map[int]int{}, []int{}, map[int]int{}, []int{}, map[int]int{}, map[int][]LineItem{} for _, pos := range positions { tmpXMap[pos[0]]++ tmpXMap[pos[2]]++ } for k := range tmpXMap { posXArray = append(posXArray, k) } sort.Ints(posXArray) for i, pos := range posXArray { posXMap[pos] = i } for _, pos := range positions { tmpYMap[pos[1]]++ tmpYMap[pos[3]]++ tmp1 := lines[posXMap[pos[0]]] tmp1 = append(tmp1, LineItem{start: pos[1], end: pos[3], state: 1}) lines[posXMap[pos[0]]] = tmp1 tmp2 := lines[posXMap[pos[2]]] tmp2 = append(tmp2, LineItem{start: pos[1], end: pos[3], state: -1}) lines[posXMap[pos[2]]] = tmp2 } for k := range tmpYMap { posYArray = append(posYArray, k) } sort.Ints(posYArray) for i, pos := range posYArray { posYMap[pos] = i } return posXMap, posXArray, posYMap, posYArray, lines } // LineItem define type LineItem struct { // 垂直于 x 轴的线段 start, end, state int // state = 1 代表进入,-1 代表离开 } // SegmentItem define type SegmentItem struct { count int val int } // SegmentAreaTree define type SegmentAreaTree struct { data []int tree []SegmentItem left, right int merge func(i, j int) int } // Init define func (sat *SegmentAreaTree) Init(nums []int, oper func(i, j int) int) { sat.merge = oper data, tree := make([]int, len(nums)), make([]SegmentItem, 4*len(nums)) for i := 0; i < len(nums); i++ { data[i] = nums[i] } sat.data, sat.tree = data, tree if len(nums) > 0 { sat.buildSegmentTree(0, 0, len(nums)-1) } } // 在 treeIndex 的位置创建 [left....right] 区间的线段树 func (sat *SegmentAreaTree) buildSegmentTree(treeIndex, left, right int) { if left == right-1 { sat.tree[treeIndex] = SegmentItem{count: 0, val: sat.data[left]} return } midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, sat.leftChild(treeIndex), sat.rightChild(treeIndex) sat.buildSegmentTree(leftTreeIndex, left, midTreeIndex) sat.buildSegmentTree(rightTreeIndex, midTreeIndex, right) sat.pushUp(treeIndex, leftTreeIndex, rightTreeIndex) } func (sat *SegmentAreaTree) pushUp(treeIndex, leftTreeIndex, rightTreeIndex int) { newCount, newValue := sat.merge(sat.tree[leftTreeIndex].count, sat.tree[rightTreeIndex].count), 0 if sat.tree[leftTreeIndex].count > 0 && sat.tree[rightTreeIndex].count > 0 { newValue = sat.merge(sat.tree[leftTreeIndex].val, sat.tree[rightTreeIndex].val) } else if sat.tree[leftTreeIndex].count > 0 && sat.tree[rightTreeIndex].count == 0 { newValue = sat.tree[leftTreeIndex].val } else if sat.tree[leftTreeIndex].count == 0 && sat.tree[rightTreeIndex].count > 0 { newValue = sat.tree[rightTreeIndex].val } sat.tree[treeIndex] = SegmentItem{count: newCount, val: newValue} } func (sat *SegmentAreaTree) leftChild(index int) int { return 2*index + 1 } func (sat *SegmentAreaTree) rightChild(index int) int { return 2*index + 2 } // 查询 [left....right] 区间内的值 // Query define func (sat *SegmentAreaTree) Query(left, right int) int { if len(sat.data) > 0 { return sat.queryInTree(0, 0, len(sat.data)-1, left, right) } return 0 } func (sat *SegmentAreaTree) queryInTree(treeIndex, left, right, queryLeft, queryRight int) int { midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, sat.leftChild(treeIndex), sat.rightChild(treeIndex) if left > queryRight || right < queryLeft { // segment completely outside range return 0 // represents a null node } if queryLeft <= left && queryRight >= right { // segment completely inside range if sat.tree[treeIndex].count > 0 { return sat.tree[treeIndex].val } return 0 } if queryLeft > midTreeIndex { return sat.queryInTree(rightTreeIndex, midTreeIndex, right, queryLeft, queryRight) } else if queryRight <= midTreeIndex { return sat.queryInTree(leftTreeIndex, left, midTreeIndex, queryLeft, queryRight) } // merge query results return sat.merge(sat.queryInTree(leftTreeIndex, left, midTreeIndex, queryLeft, midTreeIndex), sat.queryInTree(rightTreeIndex, midTreeIndex, right, midTreeIndex, queryRight)) } // Update define func (sat *SegmentAreaTree) Update(updateLeft, updateRight, val int) { if len(sat.data) > 0 { sat.updateInTree(0, 0, len(sat.data)-1, updateLeft, updateRight, val) } } func (sat *SegmentAreaTree) updateInTree(treeIndex, left, right, updateLeft, updateRight, val int) { midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, sat.leftChild(treeIndex), sat.rightChild(treeIndex) if left > right || left >= updateRight || right <= updateLeft { // 由于叶子节点的区间不在是 left == right 所以这里判断需要增加等号的判断 return // out of range. escape. } if updateLeft <= left && right <= updateRight { // segment is fully within update range if left == right-1 { sat.tree[treeIndex].count = sat.merge(sat.tree[treeIndex].count, val) } if left != right-1 { // update lazy[] for children sat.updateInTree(leftTreeIndex, left, midTreeIndex, updateLeft, updateRight, val) sat.updateInTree(rightTreeIndex, midTreeIndex, right, updateLeft, updateRight, val) sat.pushUp(treeIndex, leftTreeIndex, rightTreeIndex) } return } sat.updateInTree(leftTreeIndex, left, midTreeIndex, updateLeft, updateRight, val) sat.updateInTree(rightTreeIndex, midTreeIndex, right, updateLeft, updateRight, val) // merge updates sat.pushUp(treeIndex, leftTreeIndex, rightTreeIndex) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0058.Length-of-Last-Word/58.Length of Last Word_test.go
leetcode/0058.Length-of-Last-Word/58.Length of Last Word_test.go
package leetcode import ( "fmt" "testing" ) type question58 struct { para58 ans58 } // para 是参数 type para58 struct { s string } // ans 是答案 type ans58 struct { ans int } func Test_Problem58(t *testing.T) { qs := []question58{ { para58{"Hello World"}, ans58{5}, }, { para58{" fly me to the moon "}, ans58{4}, }, { para58{"luffy is still joyboy"}, ans58{6}, }, } fmt.Printf("------------------------Leetcode Problem 58------------------------\n") for _, q := range qs { _, p := q.ans58, q.para58 fmt.Printf("【input】:%v 【output】:%v\n", p, lengthOfLastWord(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/0058.Length-of-Last-Word/58.Length of Last Word.go
leetcode/0058.Length-of-Last-Word/58.Length of Last Word.go
package leetcode func lengthOfLastWord(s string) int { last := len(s) - 1 for last >= 0 && s[last] == ' ' { last-- } if last < 0 { return 0 } first := last for first >= 0 && s[first] != ' ' { first-- } return last - first }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1122.Relative-Sort-Array/1122. Relative Sort Array_test.go
leetcode/1122.Relative-Sort-Array/1122. Relative Sort Array_test.go
package leetcode import ( "fmt" "testing" ) type question1122 struct { para1122 ans1122 } // para 是参数 // one 代表第一个参数 type para1122 struct { arr1 []int arr2 []int } // ans 是答案 // one 代表第一个答案 type ans1122 struct { one []int } func Test_Problem1122(t *testing.T) { qs := []question1122{ { para1122{[]int{2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19}, []int{2, 1, 4, 3, 9, 6}}, ans1122{[]int{2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19}}, }, } fmt.Printf("------------------------Leetcode Problem 1122------------------------\n") for _, q := range qs { _, p := q.ans1122, q.para1122 fmt.Printf("【input】:%v 【output】:%v\n", p, relativeSortArray(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/1122.Relative-Sort-Array/1122. Relative Sort Array.go
leetcode/1122.Relative-Sort-Array/1122. Relative Sort Array.go
package leetcode import "sort" // 解法一 桶排序,时间复杂度 O(n^2) func relativeSortArray(A, B []int) []int { count := [1001]int{} for _, a := range A { count[a]++ } res := make([]int, 0, len(A)) for _, b := range B { for count[b] > 0 { res = append(res, b) count[b]-- } } for i := 0; i < 1001; i++ { for count[i] > 0 { res = append(res, i) count[i]-- } } return res } // 解法二 模拟,时间复杂度 O(n^2) func relativeSortArray1(arr1 []int, arr2 []int) []int { leftover, m, res := []int{}, make(map[int]int), []int{} for _, v := range arr1 { m[v]++ } for _, s := range arr2 { count := m[s] for i := 0; i < count; i++ { res = append(res, s) } m[s] = 0 } for v, count := range m { for i := 0; i < count; i++ { leftover = append(leftover, v) } } sort.Ints(leftover) res = append(res, leftover...) return res }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0717.1-bit-and-2-bit-Characters/717. 1-bit and 2-bit Characters_test.go
leetcode/0717.1-bit-and-2-bit-Characters/717. 1-bit and 2-bit Characters_test.go
package leetcode import ( "fmt" "testing" ) type question717 struct { para717 ans717 } // para 是参数 // one 代表第一个参数 type para717 struct { one []int } // ans 是答案 // one 代表第一个答案 type ans717 struct { one bool } func Test_Problem717(t *testing.T) { qs := []question717{ { para717{[]int{1, 0, 0}}, ans717{true}, }, { para717{[]int{1, 1, 1, 0}}, ans717{false}, }, { para717{[]int{0, 1, 1, 1, 0, 0}}, ans717{true}, }, { para717{[]int{1, 1, 1, 1, 0}}, ans717{true}, }, } fmt.Printf("------------------------Leetcode Problem 717------------------------\n") for _, q := range qs { _, p := q.ans717, q.para717 fmt.Printf("【input】:%v 【output】:%v\n", p, isOneBitCharacter(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/0717.1-bit-and-2-bit-Characters/717. 1-bit and 2-bit Characters.go
leetcode/0717.1-bit-and-2-bit-Characters/717. 1-bit and 2-bit Characters.go
package leetcode func isOneBitCharacter(bits []int) bool { var i int for i = 0; i < len(bits)-1; i++ { if bits[i] == 1 { i++ } } return i == len(bits)-1 }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1736.Latest-Time-by-Replacing-Hidden-Digits/1736. Latest Time by Replacing Hidden Digits_test.go
leetcode/1736.Latest-Time-by-Replacing-Hidden-Digits/1736. Latest Time by Replacing Hidden Digits_test.go
package leetcode import ( "fmt" "testing" ) type question1736 struct { para1736 ans1736 } // para 是参数 // one 代表第一个参数 type para1736 struct { time string } // ans 是答案 // one 代表第一个答案 type ans1736 struct { one string } func Test_Problem1736(t *testing.T) { qs := []question1736{ { para1736{"2?:?0"}, ans1736{"23:50"}, }, { para1736{"0?:3?"}, ans1736{"09:39"}, }, { para1736{"1?:22"}, ans1736{"19:22"}, }, } fmt.Printf("------------------------Leetcode Problem 1736------------------------\n") for _, q := range qs { _, p := q.ans1736, q.para1736 fmt.Printf("【input】:%v 【output】:%v\n", p, maximumTime(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/1736.Latest-Time-by-Replacing-Hidden-Digits/1736. Latest Time by Replacing Hidden Digits.go
leetcode/1736.Latest-Time-by-Replacing-Hidden-Digits/1736. Latest Time by Replacing Hidden Digits.go
package leetcode func maximumTime(time string) string { timeb := []byte(time) if timeb[3] == '?' { timeb[3] = '5' } if timeb[4] == '?' { timeb[4] = '9' } if timeb[0] == '?' { if int(timeb[1]-'0') > 3 && int(timeb[1]-'0') < 10 { timeb[0] = '1' } else { timeb[0] = '2' } } if timeb[1] == '?' { timeb[1] = '9' } if timeb[0] == '2' && timeb[1] == '9' { timeb[1] = '3' } return string(timeb) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0979.Distribute-Coins-in-Binary-Tree/979. Distribute Coins in Binary Tree.go
leetcode/0979.Distribute-Coins-in-Binary-Tree/979. Distribute Coins in Binary Tree.go
package leetcode import ( "github.com/halfrost/LeetCode-Go/structures" ) // TreeNode define type TreeNode = structures.TreeNode /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func distributeCoins(root *TreeNode) int { res := 0 distributeCoinsDFS(root, &res) return res } func distributeCoinsDFS(root *TreeNode, res *int) int { if root == nil { return 0 } left, right := distributeCoinsDFS(root.Left, res), distributeCoinsDFS(root.Right, res) *res += abs(left) + abs(right) return left + right + root.Val - 1 } 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/0979.Distribute-Coins-in-Binary-Tree/979. Distribute Coins in Binary Tree_test.go
leetcode/0979.Distribute-Coins-in-Binary-Tree/979. Distribute Coins in Binary Tree_test.go
package leetcode import ( "fmt" "testing" "github.com/halfrost/LeetCode-Go/structures" ) type question979 struct { para979 ans979 } // para 是参数 // one 代表第一个参数 type para979 struct { one []int } // ans 是答案 // one 代表第一个答案 type ans979 struct { one int } func Test_Problem979(t *testing.T) { qs := []question979{ { para979{[]int{}}, ans979{0}, }, { para979{[]int{1}}, ans979{0}, }, { para979{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}}, ans979{41}, }, { para979{[]int{1, 2, 3, 4, structures.NULL, structures.NULL, 5}}, ans979{11}, }, { para979{[]int{1, 2, 3, 4, structures.NULL, 5}}, ans979{11}, }, } fmt.Printf("------------------------Leetcode Problem 979------------------------\n") for _, q := range qs { _, p := q.ans979, q.para979 fmt.Printf("【input】:%v ", p) root := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", distributeCoins(root)) } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false