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/0327.Count-of-Range-Sum/327. Count of Range Sum.go
leetcode/0327.Count-of-Range-Sum/327. Count of Range Sum.go
package leetcode import ( "sort" "github.com/halfrost/LeetCode-Go/template" ) // 解法一 线段树,时间复杂度 O(n log n) func countRangeSum(nums []int, lower int, upper int) int { if len(nums) == 0 { return 0 } st, prefixSum, sumMap, sumArray, res := template.SegmentCountTree{}, make([]int, len(nums)), make(map[int]int, 0), []int{}, 0 prefixSum[0], sumMap[nums[0]] = nums[0], nums[0] for i := 1; i < len(nums); i++ { prefixSum[i] = prefixSum[i-1] + nums[i] sumMap[prefixSum[i]] = prefixSum[i] } // sumArray 是 prefixSum 去重之后的版本,利用 sumMap 去重 for _, v := range sumMap { sumArray = append(sumArray, v) } // 排序是为了使得线段树中的区间 left <= right,如果此处不排序,线段树中的区间有很多不合法。 sort.Ints(sumArray) // 初始化线段树,节点内的值都赋值为 0,即计数为 0 st.Init(sumArray, func(i, j int) int { return 0 }) // 倒序是为了方便寻找 j,sum(i,j) 规定了 j >= i,所以倒序遍历,i 从大到小 for i := len(nums) - 1; i >= 0; i-- { // 插入的 prefixSum[i] 即是 j st.UpdateCount(prefixSum[i]) if i > 0 { res += st.Query(lower+prefixSum[i-1], upper+prefixSum[i-1]) } else { res += st.Query(lower, upper) } } return res } // 解法二 树状数组,时间复杂度 O(n log n) func countRangeSum1(nums []int, lower int, upper int) int { n := len(nums) // 计算前缀和 preSum,以及后面统计时会用到的所有数字 allNums allNums, preSum, res := make([]int, 1, 3*n+1), make([]int, n+1), 0 for i, v := range nums { preSum[i+1] = preSum[i] + v allNums = append(allNums, preSum[i+1], preSum[i+1]-lower, preSum[i+1]-upper) } // 将 allNums 离散化 sort.Ints(allNums) k := 1 kth := map[int]int{allNums[0]: k} for i := 1; i <= 3*n; i++ { if allNums[i] != allNums[i-1] { k++ kth[allNums[i]] = k } } // 遍历 preSum,利用树状数组计算每个前缀和对应的合法区间数 bit := template.BinaryIndexedTree{} bit.Init(k) bit.Add(kth[0], 1) for _, sum := range preSum[1:] { left, right := kth[sum-upper], kth[sum-lower] res += bit.Query(right) - bit.Query(left-1) bit.Add(kth[sum], 1) } return res } // 解法三 暴力,时间复杂度 O(n^2) func countRangeSum2(nums []int, lower int, upper int) int { res, n := 0, len(nums) for i := 0; i < n; i++ { tmp := 0 for j := i; j < n; j++ { if i == j { tmp = nums[i] } else { tmp += nums[j] } if tmp <= upper && tmp >= lower { 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/0327.Count-of-Range-Sum/327. Count of Range Sum_test.go
leetcode/0327.Count-of-Range-Sum/327. Count of Range Sum_test.go
package leetcode import ( "fmt" "testing" ) type question327 struct { para327 ans327 } // para 是参数 // one 代表第一个参数 type para327 struct { nums []int lower int upper int } // ans 是答案 // one 代表第一个答案 type ans327 struct { one int } func Test_Problem327(t *testing.T) { qs := []question327{ { para327{[]int{-2, 5, -1}, -2, 2}, ans327{3}, }, { para327{[]int{0, -3, -3, 1, 1, 2}, 3, 5}, ans327{2}, }, { para327{[]int{-3, 1, 2, -2, 2, -1}, -3, -1}, ans327{7}, }, } fmt.Printf("------------------------Leetcode Problem 327------------------------\n") for _, q := range qs { _, p := q.ans327, q.para327 fmt.Printf("【input】:%v 【output】:%v\n", p, countRangeSum(p.nums, p.lower, p.upper)) } 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/1200.Minimum-Absolute-Difference/1200. Minimum Absolute Difference.go
leetcode/1200.Minimum-Absolute-Difference/1200. Minimum Absolute Difference.go
package leetcode import ( "math" "sort" ) func minimumAbsDifference(arr []int) [][]int { minDiff, res := math.MaxInt32, [][]int{} sort.Ints(arr) for i := 1; i < len(arr); i++ { if arr[i]-arr[i-1] < minDiff { minDiff = arr[i] - arr[i-1] } if minDiff == 1 { break } } for i := 1; i < len(arr); i++ { if arr[i]-arr[i-1] == minDiff { res = append(res, []int{arr[i-1], arr[i]}) } } return res }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1200.Minimum-Absolute-Difference/1200. Minimum Absolute Difference_test.go
leetcode/1200.Minimum-Absolute-Difference/1200. Minimum Absolute Difference_test.go
package leetcode import ( "fmt" "testing" ) type question1200 struct { para1200 ans1200 } // para 是参数 // one 代表第一个参数 type para1200 struct { arr []int } // ans 是答案 // one 代表第一个答案 type ans1200 struct { one [][]int } func Test_Problem1200(t *testing.T) { qs := []question1200{ { para1200{[]int{4, 2, 1, 3}}, ans1200{[][]int{{1, 2}, {2, 3}, {3, 4}}}, }, { para1200{[]int{1, 3, 6, 10, 15}}, ans1200{[][]int{{1, 3}}}, }, { para1200{[]int{3, 8, -10, 23, 19, -4, -14, 27}}, ans1200{[][]int{{-14, -10}, {19, 23}, {23, 27}}}, }, } fmt.Printf("------------------------Leetcode Problem 1200------------------------\n") for _, q := range qs { _, p := q.ans1200, q.para1200 fmt.Printf("【input】:%v 【output】:%v\n", p, minimumAbsDifference(p.arr)) } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0557.Reverse-Words-in-a-String-III/557. Reverse Words in a String III.go
leetcode/0557.Reverse-Words-in-a-String-III/557. Reverse Words in a String III.go
package leetcode import ( "strings" ) func reverseWords(s string) string { ss := strings.Split(s, " ") for i, s := range ss { ss[i] = revers(s) } return strings.Join(ss, " ") } func revers(s string) string { bytes := []byte(s) i, j := 0, len(bytes)-1 for i < j { bytes[i], bytes[j] = bytes[j], bytes[i] i++ j-- } return string(bytes) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0557.Reverse-Words-in-a-String-III/557. Reverse Words in a String III_test.go
leetcode/0557.Reverse-Words-in-a-String-III/557. Reverse Words in a String III_test.go
package leetcode import ( "fmt" "testing" ) type question557 struct { para557 ans557 } // para 是参数 // one 代表第一个参数 type para557 struct { s string } // ans 是答案 // one 代表第一个答案 type ans557 struct { one string } func Test_Problem557(t *testing.T) { qs := []question557{ { para557{"Let's take LeetCode contest"}, ans557{"s'teL ekat edoCteeL tsetnoc"}, }, { para557{""}, ans557{""}, }, } fmt.Printf("------------------------Leetcode Problem 557------------------------\n") for _, q := range qs { _, p := q.ans557, q.para557 fmt.Printf("【input】:%v 【output】:%v\n", p, reverseWords(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/1160.Find-Words-That-Can-Be-Formed-by-Characters/1160. Find Words That Can Be Formed by Characters_test.go
leetcode/1160.Find-Words-That-Can-Be-Formed-by-Characters/1160. Find Words That Can Be Formed by Characters_test.go
package leetcode import ( "fmt" "testing" ) type question1160 struct { para1160 ans1160 } // para 是参数 // one 代表第一个参数 type para1160 struct { words []string chars string } // ans 是答案 // one 代表第一个答案 type ans1160 struct { one int } func Test_Problem1160(t *testing.T) { qs := []question1160{ { para1160{[]string{"cat", "bt", "hat", "tree"}, "atach"}, ans1160{6}, }, { para1160{[]string{"hello", "world", "leetcode"}, "welldonehoneyr"}, ans1160{10}, }, } fmt.Printf("------------------------Leetcode Problem 1160------------------------\n") for _, q := range qs { _, p := q.ans1160, q.para1160 fmt.Printf("【input】:%v 【output】:%v\n", p, countCharacters(p.words, p.chars)) } 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/1160.Find-Words-That-Can-Be-Formed-by-Characters/1160. Find Words That Can Be Formed by Characters.go
leetcode/1160.Find-Words-That-Can-Be-Formed-by-Characters/1160. Find Words That Can Be Formed by Characters.go
package leetcode func countCharacters(words []string, chars string) int { count, res := make([]int, 26), 0 for i := 0; i < len(chars); i++ { count[chars[i]-'a']++ } for _, w := range words { if canBeFormed(w, count) { res += len(w) } } return res } func canBeFormed(w string, c []int) bool { count := make([]int, 26) for i := 0; i < len(w); i++ { count[w[i]-'a']++ if count[w[i]-'a'] > c[w[i]-'a'] { return false } } return true }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0862.Shortest-Subarray-with-Sum-at-Least-K/862. Shortest Subarray with Sum at Least K_test.go
leetcode/0862.Shortest-Subarray-with-Sum-at-Least-K/862. Shortest Subarray with Sum at Least K_test.go
package leetcode import ( "fmt" "testing" ) type question862 struct { para862 ans862 } // para 是参数 // one 代表第一个参数 type para862 struct { A []int K int } // ans 是答案 // one 代表第一个答案 type ans862 struct { one int } func Test_Problem862(t *testing.T) { qs := []question862{ { para862{[]int{1}, 1}, ans862{1}, }, { para862{[]int{1, 2}, 4}, ans862{-1}, }, { para862{[]int{2, -1, 2}, 3}, ans862{3}, }, } fmt.Printf("------------------------Leetcode Problem 862------------------------\n") for _, q := range qs { _, p := q.ans862, q.para862 fmt.Printf("【input】:%v 【output】:%v\n", p, shortestSubarray(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/0862.Shortest-Subarray-with-Sum-at-Least-K/862. Shortest Subarray with Sum at Least K.go
leetcode/0862.Shortest-Subarray-with-Sum-at-Least-K/862. Shortest Subarray with Sum at Least K.go
package leetcode func shortestSubarray(A []int, K int) int { res, prefixSum := len(A)+1, make([]int, len(A)+1) for i := 0; i < len(A); i++ { prefixSum[i+1] = prefixSum[i] + A[i] } // deque 中保存递增的 prefixSum 下标 deque := []int{} for i := range prefixSum { // 下面这个循环希望能找到 [deque[0], i] 区间内累加和 >= K,如果找到了就更新答案 for len(deque) > 0 && prefixSum[i]-prefixSum[deque[0]] >= K { length := i - deque[0] if res > length { res = length } // 找到第一个 deque[0] 能满足条件以后,就移除它,因为它是最短长度的子序列了 deque = deque[1:] } // 下面这个循环希望能保证 prefixSum[deque[i]] 递增 for len(deque) > 0 && prefixSum[i] <= prefixSum[deque[len(deque)-1]] { deque = deque[:len(deque)-1] } deque = append(deque, i) } if res <= len(A) { return res } return -1 }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0354.Russian-Doll-Envelopes/354. Russian Doll Envelopes_test.go
leetcode/0354.Russian-Doll-Envelopes/354. Russian Doll Envelopes_test.go
package leetcode import ( "fmt" "testing" ) type question354 struct { para354 ans354 } // para 是参数 // one 代表第一个参数 type para354 struct { envelopes [][]int } // ans 是答案 // one 代表第一个答案 type ans354 struct { one int } func Test_Problem354(t *testing.T) { qs := []question354{ { para354{[][]int{{5, 4}, {6, 4}, {6, 7}, {2, 3}}}, ans354{3}, }, } fmt.Printf("------------------------Leetcode Problem 354------------------------\n") for _, q := range qs { _, p := q.ans354, q.para354 fmt.Printf("【input】:%v 【output】:%v\n", p, maxEnvelopes(p.envelopes)) } 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/0354.Russian-Doll-Envelopes/354. Russian Doll Envelopes.go
leetcode/0354.Russian-Doll-Envelopes/354. Russian Doll Envelopes.go
package leetcode import ( "sort" ) type sortEnvelopes [][]int func (s sortEnvelopes) Len() int { return len(s) } func (s sortEnvelopes) Less(i, j int) bool { if s[i][0] == s[j][0] { return s[i][1] > s[j][1] } return s[i][0] < s[j][0] } func (s sortEnvelopes) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func maxEnvelopes(envelopes [][]int) int { sort.Sort(sortEnvelopes(envelopes)) dp := []int{} for _, e := range envelopes { low, high := 0, len(dp) for low < high { mid := low + (high-low)>>1 if dp[mid] >= e[1] { high = mid } else { low = mid + 1 } } if low == len(dp) { dp = append(dp, e[1]) } else { dp[low] = e[1] } } return len(dp) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0762.Prime-Number-of-Set-Bits-in-Binary-Representation/762. Prime Number of Set Bits in Binary Representation_test.go
leetcode/0762.Prime-Number-of-Set-Bits-in-Binary-Representation/762. Prime Number of Set Bits in Binary Representation_test.go
package leetcode import ( "fmt" "testing" ) type question762 struct { para762 ans762 } // para 是参数 // one 代表第一个参数 type para762 struct { l int r int } // ans 是答案 // one 代表第一个答案 type ans762 struct { one int } func Test_Problem762(t *testing.T) { qs := []question762{ { para762{6, 10}, ans762{4}, }, { para762{10, 15}, ans762{5}, }, } fmt.Printf("------------------------Leetcode Problem 762------------------------\n") for _, q := range qs { _, p := q.ans762, q.para762 fmt.Printf("【input】:%v 【output】:%v\n", p, countPrimeSetBits(p.l, p.r)) } 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/0762.Prime-Number-of-Set-Bits-in-Binary-Representation/762. Prime Number of Set Bits in Binary Representation.go
leetcode/0762.Prime-Number-of-Set-Bits-in-Binary-Representation/762. Prime Number of Set Bits in Binary Representation.go
package leetcode import "math/bits" func countPrimeSetBits(L int, R int) int { counter := 0 for i := L; i <= R; i++ { if isPrime(bits.OnesCount(uint(i))) { counter++ } } return counter } func isPrime(x int) bool { return x == 2 || x == 3 || x == 5 || x == 7 || x == 11 || x == 13 || x == 17 || x == 19 }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0208.Implement-Trie-Prefix-Tree/208. Implement Trie (Prefix Tree)_test.go
leetcode/0208.Implement-Trie-Prefix-Tree/208. Implement Trie (Prefix Tree)_test.go
package leetcode import ( "fmt" "testing" ) func Test_Problem208(t *testing.T) { obj := Constructor208() fmt.Printf("obj = %v\n", obj) obj.Insert("apple") fmt.Printf("obj = %v\n", obj) param1 := obj.Search("apple") fmt.Printf("param_1 = %v obj = %v\n", param1, obj) param2 := obj.Search("app") fmt.Printf("param_2 = %v obj = %v\n", param2, obj) param3 := obj.StartsWith("app") fmt.Printf("param_3 = %v obj = %v\n", param3, obj) obj.Insert("app") fmt.Printf("obj = %v\n", obj) param4 := obj.Search("app") fmt.Printf("param_4 = %v obj = %v\n", param4, obj) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0208.Implement-Trie-Prefix-Tree/208. Implement Trie (Prefix Tree).go
leetcode/0208.Implement-Trie-Prefix-Tree/208. Implement Trie (Prefix Tree).go
package leetcode type Trie struct { isWord bool children map[rune]*Trie } /** Initialize your data structure here. */ func Constructor208() Trie { return Trie{isWord: false, children: make(map[rune]*Trie)} } /** Inserts a word into the trie. */ func (this *Trie) Insert(word string) { parent := this for _, ch := range word { if child, ok := parent.children[ch]; ok { parent = child } else { newChild := &Trie{children: make(map[rune]*Trie)} parent.children[ch] = newChild parent = newChild } } parent.isWord = true } /** Returns if the word is in the trie. */ func (this *Trie) Search(word string) bool { parent := this for _, ch := range word { if child, ok := parent.children[ch]; ok { parent = child continue } return false } return parent.isWord } /** Returns if there is any word in the trie that starts with the given prefix. */ func (this *Trie) StartsWith(prefix string) bool { parent := this for _, ch := range prefix { if child, ok := parent.children[ch]; ok { parent = child continue } return false } return true } /** * Your Trie object will be instantiated and called as such: * obj := Constructor(); * obj.Insert(word); * param_2 := obj.Search(word); * param_3 := obj.StartsWith(prefix); */
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0222.Count-Complete-Tree-Nodes/222. Count Complete Tree Nodes.go
leetcode/0222.Count-Complete-Tree-Nodes/222. Count Complete Tree Nodes.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 countNodes(root *TreeNode) int { if root == nil { return 0 } queue := []*TreeNode{} queue = append(queue, root) curNum, nextLevelNum, res := 1, 0, 1 for len(queue) != 0 { if curNum > 0 { node := queue[0] if node.Left != nil { queue = append(queue, node.Left) nextLevelNum++ } if node.Right != nil { queue = append(queue, node.Right) nextLevelNum++ } curNum-- queue = queue[1:] } if curNum == 0 { res += nextLevelNum curNum = nextLevelNum nextLevelNum = 0 } } return res }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0222.Count-Complete-Tree-Nodes/222. Count Complete Tree Nodes_test.go
leetcode/0222.Count-Complete-Tree-Nodes/222. Count Complete Tree Nodes_test.go
package leetcode import ( "fmt" "testing" "github.com/halfrost/LeetCode-Go/structures" ) type question222 struct { para222 ans222 } // para 是参数 // one 代表第一个参数 type para222 struct { one []int } // ans 是答案 // one 代表第一个答案 type ans222 struct { one int } func Test_Problem222(t *testing.T) { qs := []question222{ { para222{[]int{}}, ans222{0}, }, { para222{[]int{1}}, ans222{1}, }, { para222{[]int{1, 2, 3}}, ans222{3}, }, { para222{[]int{1, 2, 3, 4, 5, 6}}, ans222{6}, }, } fmt.Printf("------------------------Leetcode Problem 222------------------------\n") for _, q := range qs { _, p := q.ans222, q.para222 fmt.Printf("【input】:%v ", p) rootOne := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", countNodes(rootOne)) } 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/1184.Distance-Between-Bus-Stops/1184. Distance Between Bus Stops.go
leetcode/1184.Distance-Between-Bus-Stops/1184. Distance Between Bus Stops.go
package leetcode func distanceBetweenBusStops(distance []int, start int, destination int) int { clockwiseDis, counterclockwiseDis, n := 0, 0, len(distance) for i := start; i != destination; i = (i + 1) % n { clockwiseDis += distance[i] } for i := destination; i != start; i = (i + 1) % n { counterclockwiseDis += distance[i] } if clockwiseDis < counterclockwiseDis { return clockwiseDis } return counterclockwiseDis }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1184.Distance-Between-Bus-Stops/1184. Distance Between Bus Stops_test.go
leetcode/1184.Distance-Between-Bus-Stops/1184. Distance Between Bus Stops_test.go
package leetcode import ( "fmt" "testing" ) type question1184 struct { para1184 ans1184 } // para 是参数 // one 代表第一个参数 type para1184 struct { distance []int start int destination int } // ans 是答案 // one 代表第一个答案 type ans1184 struct { one int } func Test_Problem1184(t *testing.T) { qs := []question1184{ { para1184{[]int{1, 2, 3, 4}, 0, 1}, ans1184{1}, }, { para1184{[]int{1, 2, 3, 4}, 0, 2}, ans1184{3}, }, { para1184{[]int{1, 2, 3, 4}, 0, 3}, ans1184{4}, }, } fmt.Printf("------------------------Leetcode Problem 1184------------------------\n") for _, q := range qs { _, p := q.ans1184, q.para1184 fmt.Printf("【input】:%v 【output】:%v\n", p, distanceBetweenBusStops(p.distance, p.start, p.destination)) } 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/0684.Redundant-Connection/684. Redundant Connection_test.go
leetcode/0684.Redundant-Connection/684. Redundant Connection_test.go
package leetcode import ( "fmt" "testing" ) type question684 struct { para684 ans684 } // para 是参数 // one 代表第一个参数 type para684 struct { one [][]int } // ans 是答案 // one 代表第一个答案 type ans684 struct { one []int } func Test_Problem684(t *testing.T) { qs := []question684{ { para684{[][]int{{1, 2}, {1, 3}, {2, 3}}}, ans684{[]int{2, 3}}, }, { para684{[][]int{{1, 2}, {2, 3}, {3, 4}, {1, 4}, {1, 5}}}, ans684{[]int{1, 4}}, }, } fmt.Printf("------------------------Leetcode Problem 684------------------------\n") for _, q := range qs { _, p := q.ans684, q.para684 fmt.Printf("【input】:%v 【output】:%v\n", p, findRedundantConnection(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/0684.Redundant-Connection/684. Redundant Connection.go
leetcode/0684.Redundant-Connection/684. Redundant Connection.go
package leetcode import ( "github.com/halfrost/LeetCode-Go/template" ) func findRedundantConnection(edges [][]int) []int { if len(edges) == 0 { return []int{} } uf, res := template.UnionFind{}, []int{} uf.Init(len(edges) + 1) for i := 0; i < len(edges); i++ { if uf.Find(edges[i][0]) != uf.Find(edges[i][1]) { uf.Union(edges[i][0], edges[i][1]) } else { res = append(res, edges[i][0]) res = append(res, edges[i][1]) } } return res }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0371.Sum-of-Two-Integers/371. Sum of Two Integers.go
leetcode/0371.Sum-of-Two-Integers/371. Sum of Two Integers.go
package leetcode func getSum(a int, b int) int { if a == 0 { return b } if b == 0 { return a } // (a & b)<<1 计算的是进位 // a ^ b 计算的是不带进位的加法 return getSum((a&b)<<1, a^b) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0371.Sum-of-Two-Integers/371. Sum of Two Integers_test.go
leetcode/0371.Sum-of-Two-Integers/371. Sum of Two Integers_test.go
package leetcode import ( "fmt" "testing" ) type question371 struct { para371 ans371 } // para 是参数 // one 代表第一个参数 type para371 struct { a int b int } // ans 是答案 // one 代表第一个答案 type ans371 struct { one int } func Test_Problem371(t *testing.T) { qs := []question371{ { para371{1, 2}, ans371{3}, }, { para371{-2, 3}, ans371{1}, }, // 如需多个测试,可以复制上方元素。 } fmt.Printf("------------------------Leetcode Problem 371------------------------\n") for _, q := range qs { _, p := q.ans371, q.para371 fmt.Printf("【input】:%v 【output】:%v\n", p, getSum(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/0136.Single-Number/136. Single Number_test.go
leetcode/0136.Single-Number/136. Single Number_test.go
package leetcode import ( "fmt" "testing" ) type question136 struct { para136 ans136 } // para 是参数 // one 代表第一个参数 type para136 struct { s []int } // ans 是答案 // one 代表第一个答案 type ans136 struct { one int } func Test_Problem136(t *testing.T) { qs := []question136{ { para136{[]int{2, 2, 1}}, ans136{1}, }, { para136{[]int{4, 1, 2, 1, 2}}, ans136{4}, }, } fmt.Printf("------------------------Leetcode Problem 136------------------------\n") for _, q := range qs { _, p := q.ans136, q.para136 fmt.Printf("【input】:%v 【output】:%v\n", p, singleNumber(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/0136.Single-Number/136. Single Number.go
leetcode/0136.Single-Number/136. Single Number.go
package leetcode func singleNumber(nums []int) int { result := 0 for i := 0; i < len(nums); i++ { result ^= nums[i] } return result }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0174.Dungeon-Game/174. Dungeon Game.go
leetcode/0174.Dungeon-Game/174. Dungeon Game.go
package leetcode import "math" // 解法一 动态规划 func calculateMinimumHP(dungeon [][]int) int { if len(dungeon) == 0 { return 0 } m, n := len(dungeon), len(dungeon[0]) dp := make([][]int, m) for i := 0; i < m; i++ { dp[i] = make([]int, n) } dp[m-1][n-1] = max(1-dungeon[m-1][n-1], 1) for i := n - 2; i >= 0; i-- { dp[m-1][i] = max(1, dp[m-1][i+1]-dungeon[m-1][i]) } for i := m - 2; i >= 0; i-- { dp[i][n-1] = max(1, dp[i+1][n-1]-dungeon[i][n-1]) } for i := m - 2; i >= 0; i-- { for j := n - 2; j >= 0; j-- { dp[i][j] = min(max(1, dp[i][j+1]-dungeon[i][j]), max(1, dp[i+1][j]-dungeon[i][j])) } } return dp[0][0] } func max(a int, b int) int { if a > b { return a } return b } func min(a int, b int) int { if a > b { return b } return a } // 解法二 二分搜索 func calculateMinimumHP1(dungeon [][]int) int { low, high := 1, math.MaxInt64 for low < high { mid := low + (high-low)>>1 if canCross(dungeon, mid) { high = mid } else { low = mid + 1 } } return low } func canCross(dungeon [][]int, start int) bool { m, n := len(dungeon), len(dungeon[0]) dp := make([][]int, m) for i := 0; i < m; i++ { dp[i] = make([]int, n) } for i := 0; i < len(dp); i++ { for j := 0; j < len(dp[i]); j++ { if i == 0 && j == 0 { dp[i][j] = start + dungeon[0][0] } else { a, b := math.MinInt64, math.MinInt64 if i > 0 && dp[i-1][j] > 0 { a = dp[i-1][j] + dungeon[i][j] } if j > 0 && dp[i][j-1] > 0 { b = dp[i][j-1] + dungeon[i][j] } dp[i][j] = max(a, b) } } } return dp[m-1][n-1] > 0 }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0174.Dungeon-Game/174. Dungeon Game_test.go
leetcode/0174.Dungeon-Game/174. Dungeon Game_test.go
package leetcode import ( "fmt" "testing" ) type question174 struct { para174 ans174 } // para 是参数 // one 代表第一个参数 type para174 struct { s [][]int } // ans 是答案 // one 代表第一个答案 type ans174 struct { one int } func Test_Problem174(t *testing.T) { qs := []question174{ { para174{[][]int{{2, 1}, {1, -1}}}, ans174{1}, }, { para174{[][]int{{-3, 5}}}, ans174{4}, }, { para174{[][]int{{100}}}, ans174{1}, }, { para174{[][]int{{-2, -3, 3}, {-5, -10, 1}, {10, 30, -5}}}, ans174{7}, }, } fmt.Printf("------------------------Leetcode Problem 174------------------------\n") for _, q := range qs { _, p := q.ans174, q.para174 fmt.Printf("【input】:%v 【output】:%v\n", p, calculateMinimumHP1(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/0867.Transpose-Matrix/867. Transpose Matrix.go
leetcode/0867.Transpose-Matrix/867. Transpose Matrix.go
package leetcode func transpose(A [][]int) [][]int { row, col, result := len(A), len(A[0]), make([][]int, len(A[0])) for i := range result { result[i] = make([]int, row) } for i := 0; i < row; i++ { for j := 0; j < col; j++ { result[j][i] = A[i][j] } } return result }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0867.Transpose-Matrix/867. Transpose Matrix_test.go
leetcode/0867.Transpose-Matrix/867. Transpose Matrix_test.go
package leetcode import ( "fmt" "testing" ) type question867 struct { para867 ans867 } // para 是参数 // one 代表第一个参数 type para867 struct { A [][]int } // ans 是答案 // one 代表第一个答案 type ans867 struct { B [][]int } func Test_Problem867(t *testing.T) { qs := []question867{ { para867{[][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}}, ans867{[][]int{{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}}, }, { para867{[][]int{{1, 2, 3}, {4, 5, 6}}}, ans867{[][]int{{1, 4}, {2, 5}, {3, 6}}}, }, } fmt.Printf("------------------------Leetcode Problem 867------------------------\n") for _, q := range qs { _, p := q.ans867, q.para867 fmt.Printf("【input】:%v 【output】:%v\n", p, transpose(p.A)) } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/2038.Remove-Colored-Pieces-if-Both-Neighbors-are-the-Same-Color/2038.Remove Colored Pieces if Both Neighbors are the Same Color.go
leetcode/2038.Remove-Colored-Pieces-if-Both-Neighbors-are-the-Same-Color/2038.Remove Colored Pieces if Both Neighbors are the Same Color.go
package leetcode func winnerOfGame(colors string) bool { As, Bs := 0, 0 Acont, Bcont := 0, 0 for _, color := range colors { if color == 'A' { Acont += 1 Bcont = 0 } else { Bcont += 1 Acont = 0 } if Acont >= 3 { As += Acont - 2 } if Bcont >= 3 { Bs += Bcont - 2 } } if As > Bs { 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/2038.Remove-Colored-Pieces-if-Both-Neighbors-are-the-Same-Color/2038.Remove Colored Pieces if Both Neighbors are the Same Color_test.go
leetcode/2038.Remove-Colored-Pieces-if-Both-Neighbors-are-the-Same-Color/2038.Remove Colored Pieces if Both Neighbors are the Same Color_test.go
package leetcode import ( "fmt" "testing" ) type question2038 struct { para2038 ans2038 } // para 是参数 type para2038 struct { colors string } // ans 是答案 type ans2038 struct { ans bool } func Test_Problem2038(t *testing.T) { qs := []question2038{ { para2038{"AAABABB"}, ans2038{true}, }, { para2038{"AA"}, ans2038{false}, }, { para2038{"ABBBBBBBAAA"}, ans2038{false}, }, } fmt.Printf("------------------------Leetcode Problem 2038------------------------\n") for _, q := range qs { _, p := q.ans2038, q.para2038 fmt.Printf("【input】:%v ", p.colors) fmt.Printf("【output】:%v \n", winnerOfGame(p.colors)) } 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/1648.Sell-Diminishing-Valued-Colored-Balls/1648. Sell Diminishing-Valued Colored Balls.go
leetcode/1648.Sell-Diminishing-Valued-Colored-Balls/1648. Sell Diminishing-Valued Colored Balls.go
package leetcode import ( "container/heap" ) // 解法一 贪心 + 二分搜索 func maxProfit(inventory []int, orders int) int { maxItem, thresholdValue, count, res, mod := 0, -1, 0, 0, 1000000007 for i := 0; i < len(inventory); i++ { if inventory[i] > maxItem { maxItem = inventory[i] } } low, high := 0, maxItem for low <= high { mid := low + ((high - low) >> 1) for i := 0; i < len(inventory); i++ { count += max(inventory[i]-mid, 0) } if count <= orders { thresholdValue = mid high = mid - 1 } else { low = mid + 1 } count = 0 } count = 0 for i := 0; i < len(inventory); i++ { count += max(inventory[i]-thresholdValue, 0) } count = orders - count for i := 0; i < len(inventory); i++ { if inventory[i] >= thresholdValue { if count > 0 { res += (thresholdValue + inventory[i]) * (inventory[i] - thresholdValue + 1) / 2 count-- } else { res += (thresholdValue + 1 + inventory[i]) * (inventory[i] - thresholdValue) / 2 } } } return res % mod } func max(a int, b int) int { if a > b { return a } return b } // 解法二 优先队列,超时! func maxProfit_(inventory []int, orders int) int { res, mod := 0, 1000000007 q := PriorityQueue{} for i := 0; i < len(inventory); i++ { heap.Push(&q, &Item{count: inventory[i]}) } for ; orders > 0; orders-- { item := heap.Pop(&q).(*Item) res = (res + item.count) % mod heap.Push(&q, &Item{count: item.count - 1}) } return res } // Item define type Item struct { count int } // A PriorityQueue implements heap.Interface and holds Items. type PriorityQueue []*Item func (pq PriorityQueue) Len() int { return len(pq) } func (pq PriorityQueue) Less(i, j int) bool { // 注意:因为golang中的heap是按最小堆组织的,所以count越大,Less()越小,越靠近堆顶. return pq[i].count > pq[j].count } func (pq PriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } // Push define func (pq *PriorityQueue) Push(x interface{}) { item := x.(*Item) *pq = append(*pq, item) } // Pop define func (pq *PriorityQueue) Pop() interface{} { n := len(*pq) item := (*pq)[n-1] *pq = (*pq)[:n-1] return item }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1648.Sell-Diminishing-Valued-Colored-Balls/1648. Sell Diminishing-Valued Colored Balls_test.go
leetcode/1648.Sell-Diminishing-Valued-Colored-Balls/1648. Sell Diminishing-Valued Colored Balls_test.go
package leetcode import ( "fmt" "testing" ) type question1648 struct { para1648 ans1648 } // para 是参数 // one 代表第一个参数 type para1648 struct { inventory []int orders int } // ans 是答案 // one 代表第一个答案 type ans1648 struct { one int } func Test_Problem1648(t *testing.T) { qs := []question1648{ { para1648{[]int{2, 3, 3, 4, 5}, 4}, ans1648{16}, }, { para1648{[]int{2, 5}, 4}, ans1648{14}, }, { para1648{[]int{3, 5}, 6}, ans1648{19}, }, { para1648{[]int{2, 8, 4, 10, 6}, 20}, ans1648{110}, }, { para1648{[]int{1000000000}, 1000000000}, ans1648{21}, }, } fmt.Printf("------------------------Leetcode Problem 1648------------------------\n") for _, q := range qs { _, p := q.ans1648, q.para1648 fmt.Printf("【input】:%v 【output】:%v \n", p, maxProfit(p.inventory, p.orders)) } 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/1178.Number-of-Valid-Words-for-Each-Puzzle/1178. Number of Valid Words for Each Puzzle_test.go
leetcode/1178.Number-of-Valid-Words-for-Each-Puzzle/1178. Number of Valid Words for Each Puzzle_test.go
package leetcode import ( "reflect" "testing" ) func Test_findNumOfValidWords(t *testing.T) { words1 := []string{"aaaa", "asas", "able", "ability", "actt", "actor", "access"} puzzles1 := []string{"aboveyz", "abrodyz", "abslute", "absoryz", "actresz", "gaswxyz"} type args struct { words []string puzzles []string } tests := []struct { name string args args want []int }{ // TODO: Add test cases. {"1", args{words: words1, puzzles: puzzles1}, []int{1, 1, 3, 2, 4, 0}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := findNumOfValidWords(tt.args.words, tt.args.puzzles); !reflect.DeepEqual(got, tt.want) { t.Errorf("findNumOfValidWords() = %v, want %v", got, tt.want) } }) } }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1178.Number-of-Valid-Words-for-Each-Puzzle/1178. Number of Valid Words for Each Puzzle.go
leetcode/1178.Number-of-Valid-Words-for-Each-Puzzle/1178. Number of Valid Words for Each Puzzle.go
package leetcode /* 匹配跟单词中的字母顺序,字母个数都无关,可以用 bitmap 压缩 1. 记录 word 中 利用 map 记录各种 bit 标示的个数 2. puzzles 中各个字母都不相同! 记录 bitmap,然后搜索子空间中各种 bit 标识的个数的和 因为 puzzles 长度最长是7,所以搜索空间 2^7 */ func findNumOfValidWords(words []string, puzzles []string) []int { wordBitStatusMap, res := make(map[uint32]int, 0), []int{} for _, w := range words { wordBitStatusMap[toBitMap([]byte(w))]++ } for _, p := range puzzles { var bitMap uint32 var totalNum int bitMap |= (1 << (p[0] - 'a')) //work 中要包含 p 的第一个字母 所以这个 bit 位上必须是 1 findNum([]byte(p)[1:], bitMap, &totalNum, wordBitStatusMap) res = append(res, totalNum) } return res } func toBitMap(word []byte) uint32 { var res uint32 for _, b := range word { res |= (1 << (b - 'a')) } return res } // 利用 dfs 搜索 puzzles 的子空间 func findNum(puzzles []byte, bitMap uint32, totalNum *int, m map[uint32]int) { if len(puzzles) == 0 { *totalNum = *totalNum + m[bitMap] return } //不包含 puzzles[0],即 puzzles[0] 对应 bit 是 0 findNum(puzzles[1:], bitMap, totalNum, m) //包含 puzzles[0],即 puzzles[0] 对应 bit 是 1 bitMap |= (1 << (puzzles[0] - 'a')) findNum(puzzles[1:], bitMap, totalNum, m) bitMap ^= (1 << (puzzles[0] - 'a')) //异或 清零 return }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1300.Sum-of-Mutated-Array-Closest-to-Target/1300. Sum of Mutated Array Closest to Target.go
leetcode/1300.Sum-of-Mutated-Array-Closest-to-Target/1300. Sum of Mutated Array Closest to Target.go
package leetcode func findBestValue(arr []int, target int) int { low, high := 0, 100000 for low < high { mid := low + (high-low)>>1 if calculateSum(arr, mid) < target { low = mid + 1 } else { high = mid } } if high == 100000 { res := 0 for _, num := range arr { if res < num { res = num } } return res } // 比较阈值线分别定在 left - 1 和 left 的时候与 target 的接近程度 sum1, sum2 := calculateSum(arr, low-1), calculateSum(arr, low) if target-sum1 <= sum2-target { return low - 1 } return low } func calculateSum(arr []int, mid int) int { sum := 0 for _, num := range arr { sum += min(num, mid) } return sum } 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/1300.Sum-of-Mutated-Array-Closest-to-Target/1300. Sum of Mutated Array Closest to Target_test.go
leetcode/1300.Sum-of-Mutated-Array-Closest-to-Target/1300. Sum of Mutated Array Closest to Target_test.go
package leetcode import ( "fmt" "testing" ) type question1300 struct { para1300 ans1300 } // para 是参数 // one 代表第一个参数 type para1300 struct { arr []int target int } // ans 是答案 // one 代表第一个答案 type ans1300 struct { one int } func Test_Problem1300(t *testing.T) { qs := []question1300{ { para1300{[]int{4, 9, 3}, 10}, ans1300{3}, }, { para1300{[]int{2, 3, 5}, 10}, ans1300{5}, }, // new case { para1300{[]int{2, 3, 5}, 11}, ans1300{5}, }, { para1300{[]int{60864, 25176, 27249, 21296, 20204}, 56803}, ans1300{11361}, }, } fmt.Printf("------------------------Leetcode Problem 1300------------------------\n") for _, q := range qs { _, p := q.ans1300, q.para1300 fmt.Printf("【input】:%v 【output】:%v\n", p, findBestValue(p.arr, p.target)) } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0382.Linked-List-Random-Node/382. Linked List Random Node.go
leetcode/0382.Linked-List-Random-Node/382. Linked List Random Node.go
package leetcode import ( "math/rand" "github.com/halfrost/LeetCode-Go/structures" ) // ListNode define type ListNode = structures.ListNode /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ type Solution struct { head *ListNode } /* - @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. */ func Constructor(head *ListNode) Solution { return Solution{head: head} } /** Returns a random node's value. */ func (this *Solution) GetRandom() int { scope, selectPoint, curr := 1, 0, this.head for curr != nil { if rand.Float64() < 1.0/float64(scope) { selectPoint = curr.Val } scope += 1 curr = curr.Next } return selectPoint } /** * Your Solution object will be instantiated and called as such: * obj := Constructor(head); * param_1 := obj.GetRandom(); */
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0382.Linked-List-Random-Node/382. Linked List Random Node_test.go
leetcode/0382.Linked-List-Random-Node/382. Linked List Random Node_test.go
package leetcode import ( "fmt" "testing" "github.com/halfrost/LeetCode-Go/structures" ) func Test_Problem382(t *testing.T) { header := structures.Ints2List([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}) obj := Constructor(header) fmt.Printf("obj = %v\n", structures.List2Ints(header)) param1 := obj.GetRandom() fmt.Printf("param_1 = %v\n", param1) param1 = obj.GetRandom() fmt.Printf("param_1 = %v\n", param1) param1 = obj.GetRandom() fmt.Printf("param_1 = %v\n", param1) param1 = obj.GetRandom() fmt.Printf("param_1 = %v\n", param1) param1 = obj.GetRandom() fmt.Printf("param_1 = %v\n", param1) param1 = obj.GetRandom() fmt.Printf("param_1 = %v\n", param1) 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/1465.Maximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical-Cuts/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts.go
leetcode/1465.Maximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical-Cuts/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts.go
package leetcode import "sort" func maxArea(h int, w int, horizontalCuts []int, verticalCuts []int) int { sort.Ints(horizontalCuts) sort.Ints(verticalCuts) maxw, maxl := horizontalCuts[0], verticalCuts[0] for i, c := range horizontalCuts[1:] { if c-horizontalCuts[i] > maxw { maxw = c - horizontalCuts[i] } } if h-horizontalCuts[len(horizontalCuts)-1] > maxw { maxw = h - horizontalCuts[len(horizontalCuts)-1] } for i, c := range verticalCuts[1:] { if c-verticalCuts[i] > maxl { maxl = c - verticalCuts[i] } } if w-verticalCuts[len(verticalCuts)-1] > maxl { maxl = w - verticalCuts[len(verticalCuts)-1] } return (maxw * maxl) % (1000000007) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1465.Maximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical-Cuts/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts_test.go
leetcode/1465.Maximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical-Cuts/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts_test.go
package leetcode import ( "fmt" "testing" ) type question1465 struct { para1465 ans1465 } // para 是参数 // one 代表第一个参数 type para1465 struct { h int w int horizontalCuts []int verticalCuts []int } // ans 是答案 // one 代表第一个答案 type ans1465 struct { one int } func Test_Problem1465(t *testing.T) { qs := []question1465{ { para1465{5, 4, []int{1, 2, 4}, []int{1, 3}}, ans1465{4}, }, { para1465{5, 4, []int{3, 1}, []int{1}}, ans1465{6}, }, { para1465{5, 4, []int{3}, []int{3}}, ans1465{9}, }, } fmt.Printf("------------------------Leetcode Problem 1465------------------------\n") for _, q := range qs { _, p := q.ans1465, q.para1465 fmt.Printf("【input】:%v 【output】:%v \n", p, maxArea(p.h, p.w, p.horizontalCuts, p.verticalCuts)) } 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/0783.Minimum-Distance-Between-BST-Nodes/783. Minimum Distance Between BST Nodes_test.go
leetcode/0783.Minimum-Distance-Between-BST-Nodes/783. Minimum Distance Between BST Nodes_test.go
package leetcode import ( "fmt" "testing" "github.com/halfrost/LeetCode-Go/structures" ) type question783 struct { para783 ans783 } // para 是参数 // one 代表第一个参数 type para783 struct { one []int } // ans 是答案 // one 代表第一个答案 type ans783 struct { one int } func Test_Problem783(t *testing.T) { qs := []question783{ { para783{[]int{4, 2, 6, 1, 3}}, ans783{1}, }, { para783{[]int{1, 0, 48, structures.NULL, structures.NULL, 12, 49}}, ans783{1}, }, { para783{[]int{90, 69, structures.NULL, 49, 89, structures.NULL, 52}}, ans783{1}, }, } fmt.Printf("------------------------Leetcode Problem 783------------------------\n") for _, q := range qs { _, p := q.ans783, q.para783 fmt.Printf("【input】:%v ", p) rootOne := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", minDiffInBST(rootOne)) } 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/0783.Minimum-Distance-Between-BST-Nodes/783. Minimum Distance Between BST Nodes.go
leetcode/0783.Minimum-Distance-Between-BST-Nodes/783. Minimum Distance Between BST Nodes.go
package leetcode import ( "math" "github.com/halfrost/LeetCode-Go/structures" ) // TreeNode define type TreeNode = structures.TreeNode /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func minDiffInBST(root *TreeNode) int { res, nodes := math.MaxInt16, -1 dfsBST(root, &res, &nodes) return res } func dfsBST(root *TreeNode, res, pre *int) { if root == nil { return } dfsBST(root.Left, res, pre) if *pre != -1 { *res = min(*res, abs(root.Val-*pre)) } *pre = root.Val dfsBST(root.Right, res, pre) } func min(a, b int) int { if a > b { return b } return a } func abs(a int) int { if a > 0 { return a } return -a }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0101.Symmetric-Tree/101. Symmetric Tree.go
leetcode/0101.Symmetric-Tree/101. Symmetric 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 * } */ // 解法一 dfs func isSymmetric(root *TreeNode) bool { if root == nil { return true } return isMirror(root.Left, root.Right) } func isMirror(left *TreeNode, right *TreeNode) bool { if left == nil && right == nil { return true } if left == nil || right == nil { return false } return (left.Val == right.Val) && isMirror(left.Left, right.Right) && isMirror(left.Right, right.Left) } // 解法二 func isSymmetric1(root *TreeNode) bool { if root == nil { return true } return isSameTree(invertTree(root.Left), root.Right) } func isSameTree(p *TreeNode, q *TreeNode) bool { if p == nil && q == nil { return true } else if p != nil && q != nil { if p.Val != q.Val { return false } return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) } else { return false } } func invertTree(root *TreeNode) *TreeNode { if root == nil { return nil } invertTree(root.Left) invertTree(root.Right) root.Left, root.Right = root.Right, root.Left return root }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0101.Symmetric-Tree/101. Symmetric Tree_test.go
leetcode/0101.Symmetric-Tree/101. Symmetric Tree_test.go
package leetcode import ( "fmt" "testing" "github.com/halfrost/LeetCode-Go/structures" ) type question101 struct { para101 ans101 } // para 是参数 // one 代表第一个参数 type para101 struct { one []int } // ans 是答案 // one 代表第一个答案 type ans101 struct { one bool } func Test_Problem101(t *testing.T) { qs := []question101{ { para101{[]int{3, 4, 4, 5, structures.NULL, structures.NULL, 5, 6, structures.NULL, structures.NULL, 6}}, ans101{true}, }, { para101{[]int{1, 2, 2, structures.NULL, 3, 3}}, ans101{true}, }, { para101{[]int{}}, ans101{true}, }, { para101{[]int{1}}, ans101{true}, }, { para101{[]int{1, 2, 3}}, ans101{false}, }, { para101{[]int{1, 2, 2, 3, 4, 4, 3}}, ans101{true}, }, { para101{[]int{1, 2, 2, structures.NULL, 3, structures.NULL, 3}}, ans101{false}, }, } fmt.Printf("------------------------Leetcode Problem 101------------------------\n") for _, q := range qs { _, p := q.ans101, q.para101 fmt.Printf("【input】:%v ", p) rootOne := structures.Ints2TreeNode(p.one) fmt.Printf("【output】:%v \n", isSymmetric(rootOne)) } 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/2037.Minimum-Number-of-Moves-to-Seat-Everyone/2037.Minimum Number of Moves to Seat Everyone.go
leetcode/2037.Minimum-Number-of-Moves-to-Seat-Everyone/2037.Minimum Number of Moves to Seat Everyone.go
package leetcode import "sort" func minMovesToSeat(seats []int, students []int) int { sort.Ints(seats) sort.Ints(students) n := len(students) moves := 0 for i := 0; i < n; i++ { moves += abs(seats[i], students[i]) } return moves } func abs(a, b int) int { if a > b { return a - b } return b - a }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/2037.Minimum-Number-of-Moves-to-Seat-Everyone/2037.Minimum Number of Moves to Seat Everyone_test.go
leetcode/2037.Minimum-Number-of-Moves-to-Seat-Everyone/2037.Minimum Number of Moves to Seat Everyone_test.go
package leetcode import ( "fmt" "testing" ) type question2037 struct { para2037 ans2037 } // para 是参数 type para2037 struct { seats []int students []int } // ans 是答案 type ans2037 struct { ans int } func Test_Problem2037(t *testing.T) { qs := []question2037{ { para2037{[]int{3, 1, 5}, []int{2, 7, 4}}, ans2037{4}, }, { para2037{[]int{4, 1, 5, 9}, []int{1, 3, 2, 6}}, ans2037{7}, }, { para2037{[]int{2, 2, 6, 6}, []int{1, 3, 2, 6}}, ans2037{4}, }, } fmt.Printf("------------------------Leetcode Problem 2037------------------------\n") for _, q := range qs { _, p := q.ans2037, q.para2037 fmt.Printf("【input】:%v ", p) fmt.Printf("【output】:%v \n", minMovesToSeat(p.seats, p.students)) } 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/0209.Minimum-Size-Subarray-Sum/209. Minimum Size Subarray Sum.go
leetcode/0209.Minimum-Size-Subarray-Sum/209. Minimum Size Subarray Sum.go
package leetcode func minSubArrayLen(target int, nums []int) int { left, sum, res := 0, 0, len(nums)+1 for right, v := range nums { sum += v for sum >= target { res = min(res, right-left+1) sum -= nums[left] left++ } } if res == len(nums)+1 { return 0 } return res } 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/0209.Minimum-Size-Subarray-Sum/209. Minimum Size Subarray Sum_test.go
leetcode/0209.Minimum-Size-Subarray-Sum/209. Minimum Size Subarray Sum_test.go
package leetcode import ( "fmt" "testing" ) type question209 struct { para209 ans209 } // para 是参数 // one 代表第一个参数 type para209 struct { s int one []int } // ans 是答案 // one 代表第一个答案 type ans209 struct { one int } func Test_Problem209(t *testing.T) { qs := []question209{ { para209{7, []int{2, 3, 1, 2, 4, 3}}, ans209{2}, }, } fmt.Printf("------------------------Leetcode Problem 209------------------------\n") for _, q := range qs { _, p := q.ans209, q.para209 fmt.Printf("【input】:%v 【output】:%v\n", p, minSubArrayLen(p.s, 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/0909.Snakes-and-Ladders/909. Snakes and Ladders.go
leetcode/0909.Snakes-and-Ladders/909. Snakes and Ladders.go
package leetcode type pair struct { id, step int } func snakesAndLadders(board [][]int) int { n := len(board) visited := make([]bool, n*n+1) queue := []pair{{1, 0}} for len(queue) > 0 { p := queue[0] queue = queue[1:] for i := 1; i <= 6; i++ { nxt := p.id + i if nxt > n*n { // 超出边界 break } r, c := getRowCol(nxt, n) // 得到下一步的行列 if board[r][c] > 0 { // 存在蛇或梯子 nxt = board[r][c] } if nxt == n*n { // 到达终点 return p.step + 1 } if !visited[nxt] { visited[nxt] = true queue = append(queue, pair{nxt, p.step + 1}) // 扩展新状态 } } } return -1 } func getRowCol(id, n int) (r, c int) { r, c = (id-1)/n, (id-1)%n if r%2 == 1 { c = n - 1 - c } r = n - 1 - r return r, c }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0909.Snakes-and-Ladders/909. Snakes and Ladders_test.go
leetcode/0909.Snakes-and-Ladders/909. Snakes and Ladders_test.go
package leetcode import ( "fmt" "testing" ) type question909 struct { para909 ans909 } // para 是参数 // one 代表第一个参数 type para909 struct { one [][]int } // ans 是答案 // one 代表第一个答案 type ans909 struct { one int } func Test_Problem909(t *testing.T) { qs := []question909{ { para909{[][]int{ {-1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1}, {-1, 35, -1, -1, 13, -1}, {-1, -1, -1, -1, -1, -1}, {-1, 15, -1, -1, -1, -1}, }}, ans909{4}, }, } fmt.Printf("------------------------Leetcode Problem 909------------------------\n") for _, q := range qs { _, p := q.ans909, q.para909 fmt.Printf("【input】:%v 【output】:%v\n", p, snakesAndLadders(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/0081.Search-in-Rotated-Sorted-Array-II/81. Search in Rotated Sorted Array II_test.go
leetcode/0081.Search-in-Rotated-Sorted-Array-II/81. Search in Rotated Sorted Array II_test.go
package leetcode import ( "fmt" "testing" ) type question81 struct { para81 ans81 } // para 是参数 // one 代表第一个参数 type para81 struct { nums []int target int } // ans 是答案 // one 代表第一个答案 type ans81 struct { one bool } func Test_Problem81(t *testing.T) { qs := []question81{ { para81{[]int{2, 5, 6, 0, 0, 1, 2}, 0}, ans81{true}, }, { para81{[]int{2, 5, 6, 0, 0, 1, 2}, 3}, ans81{false}, }, } fmt.Printf("------------------------Leetcode Problem 81------------------------\n") for _, q := range qs { _, p := q.ans81, q.para81 fmt.Printf("【input】:%v 【output】:%v\n", p, search(p.nums, p.target)) } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0081.Search-in-Rotated-Sorted-Array-II/81. Search in Rotated Sorted Array II.go
leetcode/0081.Search-in-Rotated-Sorted-Array-II/81. Search in Rotated Sorted Array II.go
package leetcode func search(nums []int, target int) bool { if len(nums) == 0 { return false } low, high := 0, len(nums)-1 for low <= high { mid := low + (high-low)>>1 if nums[mid] == target { return true } else if nums[mid] > nums[low] { // 在数值大的一部分区间里 if nums[low] <= target && target < nums[mid] { high = mid - 1 } else { low = mid + 1 } } else if nums[mid] < nums[high] { // 在数值小的一部分区间里 if nums[mid] < target && target <= nums[high] { low = mid + 1 } else { high = mid - 1 } } else { if nums[low] == nums[mid] { low++ } if nums[high] == nums[mid] { high-- } } } return false }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0925.Long-Pressed-Name/925. Long Pressed Name.go
leetcode/0925.Long-Pressed-Name/925. Long Pressed Name.go
package leetcode func isLongPressedName(name string, typed string) bool { if len(name) == 0 && len(typed) == 0 { return true } if (len(name) == 0 && len(typed) != 0) || (len(name) != 0 && len(typed) == 0) { return false } i, j := 0, 0 for i < len(name) && j < len(typed) { if name[i] != typed[j] { return false } for i < len(name) && j < len(typed) && name[i] == typed[j] { i++ j++ } for j < len(typed) && typed[j] == typed[j-1] { j++ } } return i == len(name) && j == len(typed) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0925.Long-Pressed-Name/925. Long Pressed Name_test.go
leetcode/0925.Long-Pressed-Name/925. Long Pressed Name_test.go
package leetcode import ( "fmt" "testing" ) type question925 struct { para925 ans925 } // para 是参数 // one 代表第一个参数 type para925 struct { name string typed string } // ans 是答案 // one 代表第一个答案 type ans925 struct { one bool } func Test_Problem925(t *testing.T) { qs := []question925{ { para925{"alex", "aaleex"}, ans925{true}, }, { para925{"alex", "alexxr"}, ans925{false}, }, { para925{"alex", "alexxxxr"}, ans925{false}, }, { para925{"alex", "alexxxxx"}, ans925{true}, }, { para925{"saeed", "ssaaedd"}, ans925{false}, }, { para925{"leelee", "lleeelee"}, ans925{true}, }, { para925{"laiden", "laiden"}, ans925{true}, }, { para925{"kikcxmvzi", "kiikcxxmmvvzz"}, ans925{false}, }, } fmt.Printf("------------------------Leetcode Problem 925------------------------\n") for _, q := range qs { _, p := q.ans925, q.para925 fmt.Printf("【input】:%v 【output】:%v\n", p, isLongPressedName(p.name, p.typed)) } 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/0520.Detect-Capital/520.Detect Capital_test.go
leetcode/0520.Detect-Capital/520.Detect Capital_test.go
package leetcode import ( "fmt" "testing" ) type question520 struct { para520 ans520 } // para 是参数 type para520 struct { word string } // ans 是答案 type ans520 struct { ans bool } func Test_Problem520(t *testing.T) { qs := []question520{ { para520{"USA"}, ans520{true}, }, { para520{"FlaG"}, ans520{false}, }, } fmt.Printf("------------------------Leetcode Problem 520------------------------\n") for _, q := range qs { _, p := q.ans520, q.para520 fmt.Printf("【input】:%v 【output】:%v\n", p, detectCapitalUse(p.word)) } 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/0520.Detect-Capital/520.Detect Capital.go
leetcode/0520.Detect-Capital/520.Detect Capital.go
package leetcode import "strings" func detectCapitalUse(word string) bool { wLower := strings.ToLower(word) wUpper := strings.ToUpper(word) wCaptial := strings.ToUpper(string(word[0])) + strings.ToLower(string(word[1:])) if wCaptial == word || wLower == word || wUpper == word { 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/1017.Convert-to-Base-2/1017. Convert to Base -2.go
leetcode/1017.Convert-to-Base-2/1017. Convert to Base -2.go
package leetcode import "strconv" func baseNeg2(N int) string { if N == 0 { return "0" } res := "" for N != 0 { remainder := N % (-2) N = N / (-2) if remainder < 0 { remainder += 2 N++ } res = strconv.Itoa(remainder) + res } return res }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1017.Convert-to-Base-2/1017. Convert to Base -2_test.go
leetcode/1017.Convert-to-Base-2/1017. Convert to Base -2_test.go
package leetcode import ( "fmt" "testing" ) type question1017 struct { para1017 ans1017 } // para 是参数 // one 代表第一个参数 type para1017 struct { one int } // ans 是答案 // one 代表第一个答案 type ans1017 struct { one string } func Test_Problem1017(t *testing.T) { qs := []question1017{ { para1017{2}, ans1017{"110"}, }, { para1017{3}, ans1017{"111"}, }, { para1017{4}, ans1017{"110"}, }, } fmt.Printf("------------------------Leetcode Problem 1017------------------------\n") for _, q := range qs { _, p := q.ans1017, q.para1017 fmt.Printf("【input】:%v 【output】:%v\n", p, baseNeg2(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/0853.Car-Fleet/853. Car Fleet.go
leetcode/0853.Car-Fleet/853. Car Fleet.go
package leetcode import ( "sort" ) type car struct { time float64 position int } // ByPosition define type ByPosition []car func (a ByPosition) Len() int { return len(a) } func (a ByPosition) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByPosition) Less(i, j int) bool { return a[i].position > a[j].position } func carFleet(target int, position []int, speed []int) int { n := len(position) if n <= 1 { return n } cars := make([]car, n) for i := 0; i < n; i++ { cars[i] = car{float64(target-position[i]) / float64(speed[i]), position[i]} } sort.Sort(ByPosition(cars)) fleet, lastTime := 0, 0.0 for i := 0; i < len(cars); i++ { if cars[i].time > lastTime { lastTime = cars[i].time fleet++ } } return fleet }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0853.Car-Fleet/853. Car Fleet_test.go
leetcode/0853.Car-Fleet/853. Car Fleet_test.go
package leetcode import ( "fmt" "testing" ) type question853 struct { para853 ans853 } // para 是参数 // one 代表第一个参数 type para853 struct { target int position []int speed []int } // ans 是答案 // one 代表第一个答案 type ans853 struct { one int } func Test_Problem853(t *testing.T) { qs := []question853{ { para853{12, []int{10, 8, 0, 5, 3}, []int{2, 4, 1, 1, 3}}, ans853{3}, }, } fmt.Printf("------------------------Leetcode Problem 853------------------------\n") for _, q := range qs { _, p := q.ans853, q.para853 fmt.Printf("【input】:%v 【output】:%v\n", p, carFleet(p.target, p.position, p.speed)) } 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/2021.Brightest-Position-on-Street/2021. Brightest Position on Street_test.go
leetcode/2021.Brightest-Position-on-Street/2021. Brightest Position on Street_test.go
package leetcode import ( "fmt" "testing" ) type question2021 struct { para2021 ans2021 } // para 是参数 type para2021 struct { lights [][]int } // ans 是答案 type ans2021 struct { ans int } func Test_Problem2021(t *testing.T) { qs := []question2021{ { para2021{[][]int{{-3, 2}, {1, 2}, {3, 3}}}, ans2021{-1}, }, { para2021{[][]int{{1, 0}, {0, 1}}}, ans2021{1}, }, { para2021{[][]int{{1, 2}}}, ans2021{-1}, }, { para2021{[][]int{{1, 1}, {2, 4}, {-1, 0}, {-3, 5}, {1, 2}}}, ans2021{-1}, }, } fmt.Printf("------------------------Leetcode Problem 2021------------------------\n") for _, q := range qs { _, p := q.ans2021, q.para2021 fmt.Printf("【input】:%v ", p) fmt.Printf("【output】:%v \n", brightestPosition(p.lights)) } 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/2021.Brightest-Position-on-Street/2021. Brightest Position on Street.go
leetcode/2021.Brightest-Position-on-Street/2021. Brightest Position on Street.go
package leetcode import ( "sort" ) type lightItem struct { index int sign int } func brightestPosition(lights [][]int) int { lightMap, lightItems := map[int]int{}, []lightItem{} for _, light := range lights { lightMap[light[0]-light[1]] += 1 lightMap[light[0]+light[1]+1] -= 1 } for k, v := range lightMap { lightItems = append(lightItems, lightItem{index: k, sign: v}) } sort.SliceStable(lightItems, func(i, j int) bool { return lightItems[i].index < lightItems[j].index }) res, border, tmp := 0, 0, 0 for _, v := range lightItems { tmp += v.sign if border < tmp { res = v.index border = tmp } } return res }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0069.Sqrtx/69. Sqrt(x).go
leetcode/0069.Sqrtx/69. Sqrt(x).go
package leetcode // 解法一 二分, 找到最后一个满足 n^2 <= x 的整数n func mySqrt(x int) int { l, r := 0, x for l < r { mid := (l + r + 1) / 2 if mid*mid > x { r = mid - 1 } else { l = mid } } return l } // 解法二 牛顿迭代法 https://en.wikipedia.org/wiki/Integer_square_root func mySqrt1(x int) int { r := x for r*r > x { r = (r + x/r) / 2 } return r } // 解法三 Quake III 游戏引擎中有一种比 STL 的 sqrt 快 4 倍的实现 https://en.wikipedia.org/wiki/Fast_inverse_square_root // float Q_rsqrt( float number ) // { // long i; // float x2, y; // const float threehalfs = 1.5F; // x2 = number * 0.5F; // y = number; // i = * ( long * ) &y; // evil floating point bit level hacking // i = 0x5f3759df - ( i >> 1 ); // what the fuck? // y = * ( float * ) &i; // y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration // // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed // return y; // }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0069.Sqrtx/69. Sqrt(x)_test.go
leetcode/0069.Sqrtx/69. Sqrt(x)_test.go
package leetcode import ( "fmt" "testing" ) type question69 struct { para69 ans69 } // para 是参数 // one 代表第一个参数 type para69 struct { one int } // ans 是答案 // one 代表第一个答案 type ans69 struct { one int } func Test_Problem69(t *testing.T) { qs := []question69{ { para69{4}, ans69{2}, }, { para69{8}, ans69{2}, }, } fmt.Printf("------------------------Leetcode Problem 69------------------------\n") for _, q := range qs { _, p := q.ans69, q.para69 fmt.Printf("【input】:%v 【output】:%v\n", p, mySqrt1(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/9990352.Data-Stream-as-Disjoint-Intervals/352. Data Stream as Disjoint Intervals.go
leetcode/9990352.Data-Stream-as-Disjoint-Intervals/352. Data Stream as Disjoint Intervals.go
package leetcode import ( "github.com/halfrost/LeetCode-Go/structures" ) // Interval define type Interval = structures.Interval // SummaryRanges define type SummaryRanges struct { intervals []Interval } // Constructor352 define func Constructor352() SummaryRanges { return SummaryRanges{} } // AddNum define func (sr *SummaryRanges) AddNum(val int) { if sr.intervals == nil { sr.intervals = []Interval{ { Start: val, End: val, }, } return } low, high := 0, len(sr.intervals)-1 for low <= high { mid := low + (high-low)>>1 if sr.intervals[mid].Start <= val && val <= sr.intervals[mid].End { return } else if val < sr.intervals[mid].Start { high = mid - 1 } else { low = mid + 1 } } if low == 0 { if sr.intervals[0].Start-1 == val { sr.intervals[0].Start-- return } ni := Interval{Start: val, End: val} sr.intervals = append(sr.intervals, ni) copy(sr.intervals[1:], sr.intervals) sr.intervals[0] = ni return } if low == len(sr.intervals) { if sr.intervals[low-1].End+1 == val { sr.intervals[low-1].End++ return } sr.intervals = append(sr.intervals, Interval{Start: val, End: val}) return } if sr.intervals[low-1].End+1 < val && val < sr.intervals[low].Start-1 { sr.intervals = append(sr.intervals, Interval{}) copy(sr.intervals[low+1:], sr.intervals[low:]) sr.intervals[low] = Interval{Start: val, End: val} return } if sr.intervals[low-1].End == val-1 && val+1 == sr.intervals[low].Start { sr.intervals[low-1].End = sr.intervals[low].End n := len(sr.intervals) copy(sr.intervals[low:], sr.intervals[low+1:]) sr.intervals = sr.intervals[:n-1] return } if sr.intervals[low-1].End == val-1 { sr.intervals[low-1].End++ } else { sr.intervals[low].Start-- } } // GetIntervals define func (sr *SummaryRanges) GetIntervals() [][]int { intervals := [][]int{} for _, interval := range sr.intervals { intervals = append(intervals, []int{interval.Start, interval.End}) } return intervals } /** * Your SummaryRanges object will be instantiated and called as such: * obj := Constructor(); * obj.AddNum(val); * param_2 := obj.GetIntervals(); */
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/9990352.Data-Stream-as-Disjoint-Intervals/352. Data Stream as Disjoint Intervals_test.go
leetcode/9990352.Data-Stream-as-Disjoint-Intervals/352. Data Stream as Disjoint Intervals_test.go
package leetcode import ( "fmt" "testing" ) func Test_Problem352(t *testing.T) { obj := Constructor352() fmt.Printf("obj = %v\n", obj) obj.AddNum(1) fmt.Printf("Intervals = %v\n", obj.GetIntervals()) // [1,1] obj.AddNum(3) fmt.Printf("Intervals = %v\n", obj.GetIntervals()) // [1,1] [3,3] obj.AddNum(7) fmt.Printf("Intervals = %v\n", obj.GetIntervals()) // [1, 1], [3, 3], [7, 7] obj.AddNum(2) fmt.Printf("Intervals = %v\n", obj.GetIntervals()) // [1, 3], [7, 7] obj.AddNum(6) fmt.Printf("Intervals = %v\n", obj.GetIntervals()) // [1, 3], [6, 7] }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1052.Grumpy-Bookstore-Owner/1052. Grumpy Bookstore Owner.go
leetcode/1052.Grumpy-Bookstore-Owner/1052. Grumpy Bookstore Owner.go
package leetcode // 解法一 滑动窗口优化版 func maxSatisfied(customers []int, grumpy []int, X int) int { customer0, customer1, maxCustomer1, left, right := 0, 0, 0, 0, 0 for ; right < len(customers); right++ { if grumpy[right] == 0 { customer0 += customers[right] } else { customer1 += customers[right] for right-left+1 > X { if grumpy[left] == 1 { customer1 -= customers[left] } left++ } if customer1 > maxCustomer1 { maxCustomer1 = customer1 } } } return maxCustomer1 + customer0 } // 解法二 滑动窗口暴力版 func maxSatisfied1(customers []int, grumpy []int, X int) int { left, right, res := 0, -1, 0 for left < len(customers) { if right+1 < len(customers) && right-left < X-1 { right++ } else { if right-left+1 == X { res = max(res, sumSatisfied(customers, grumpy, left, right)) } left++ } } return res } func max(a int, b int) int { if a > b { return a } return b } func sumSatisfied(customers []int, grumpy []int, start, end int) int { sum := 0 for i := 0; i < len(customers); i++ { if i < start || i > end { if grumpy[i] == 0 { sum += customers[i] } } else { sum += customers[i] } } return sum }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/1052.Grumpy-Bookstore-Owner/1052. Grumpy Bookstore Owner_test.go
leetcode/1052.Grumpy-Bookstore-Owner/1052. Grumpy Bookstore Owner_test.go
package leetcode import ( "fmt" "testing" ) type question1052 struct { para1052 ans1052 } // para 是参数 // one 代表第一个参数 type para1052 struct { customers []int grumpy []int x int } // ans 是答案 // one 代表第一个答案 type ans1052 struct { one int } func Test_Problem1052(t *testing.T) { qs := []question1052{ { para1052{[]int{4, 10, 10}, []int{1, 1, 0}, 2}, ans1052{24}, }, { para1052{[]int{1}, []int{0}, 1}, ans1052{1}, }, { para1052{[]int{1, 0, 1, 2, 1, 1, 7, 5}, []int{0, 1, 0, 1, 0, 1, 0, 1}, 3}, ans1052{16}, }, } fmt.Printf("------------------------Leetcode Problem 1052------------------------\n") for _, q := range qs { _, p := q.ans1052, q.para1052 fmt.Printf("【input】:%v 【output】:%v\n", p, maxSatisfied(p.customers, p.grumpy, p.x)) } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0509.Fibonacci-Number/509. Fibonacci Number.go
leetcode/0509.Fibonacci-Number/509. Fibonacci Number.go
package leetcode import "math" // 解法一 递归法 时间复杂度 O(2^n),空间复杂度 O(n) func fib(N int) int { if N <= 1 { return N } return fib(N-1) + fib(N-2) } // 解法二 自底向上的记忆化搜索 时间复杂度 O(n),空间复杂度 O(n) func fib1(N int) int { if N <= 1 { return N } cache := map[int]int{0: 0, 1: 1} for i := 2; i <= N; i++ { cache[i] = cache[i-1] + cache[i-2] } return cache[N] } // 解法三 自顶向下的记忆化搜索 时间复杂度 O(n),空间复杂度 O(n) func fib2(N int) int { if N <= 1 { return N } return memoize(N, map[int]int{0: 0, 1: 1}) } func memoize(N int, cache map[int]int) int { if _, ok := cache[N]; ok { return cache[N] } cache[N] = memoize(N-1, cache) + memoize(N-2, cache) return memoize(N, cache) } // 解法四 优化版的 dp,节约内存空间 时间复杂度 O(n),空间复杂度 O(1) func fib3(N int) int { if N <= 1 { return N } if N == 2 { return 1 } current, prev1, prev2 := 0, 1, 1 for i := 3; i <= N; i++ { current = prev1 + prev2 prev2 = prev1 prev1 = current } return current } // 解法五 矩阵快速幂 时间复杂度 O(log n),空间复杂度 O(log n) // | 1 1 | ^ n = | F(n+1) F(n) | // | 1 0 | | F(n) F(n-1) | func fib4(N int) int { if N <= 1 { return N } var A = [2][2]int{ {1, 1}, {1, 0}, } A = matrixPower(A, N-1) return A[0][0] } func matrixPower(A [2][2]int, N int) [2][2]int { if N <= 1 { return A } A = matrixPower(A, N/2) A = multiply(A, A) var B = [2][2]int{ {1, 1}, {1, 0}, } if N%2 != 0 { A = multiply(A, B) } return A } func multiply(A [2][2]int, B [2][2]int) [2][2]int { x := A[0][0]*B[0][0] + A[0][1]*B[1][0] y := A[0][0]*B[0][1] + A[0][1]*B[1][1] z := A[1][0]*B[0][0] + A[1][1]*B[1][0] w := A[1][0]*B[0][1] + A[1][1]*B[1][1] A[0][0] = x A[0][1] = y A[1][0] = z A[1][1] = w return A } // 解法六 公式法 f(n)=(1/√5)*{[(1+√5)/2]^n -[(1-√5)/2]^n},用 时间复杂度在 O(log n) 和 O(n) 之间,空间复杂度 O(1) // 经过实际测试,会发现 pow() 系统函数比快速幂慢,说明 pow() 比 O(log n) 慢 // 斐波那契数列是一个自然数的数列,通项公式却是用无理数来表达的。而且当 n 趋向于无穷大时,前一项与后一项的比值越来越逼近黄金分割 0.618(或者说后一项与前一项的比值小数部分越来越逼近 0.618)。 // 斐波那契数列用计算机计算的时候可以直接用四舍五入函数 Round 来计算。 func fib5(N int) int { var goldenRatio float64 = float64((1 + math.Sqrt(5)) / 2) return int(math.Round(math.Pow(goldenRatio, float64(N)) / math.Sqrt(5))) } // 解法七 协程版,但是时间特别慢,不推荐,放在这里只是告诉大家,写 LeetCode 算法题的时候,启动 goroutine 特别慢 func fib6(N int) int { return <-fibb(N) } func fibb(n int) <-chan int { result := make(chan int) go func() { defer close(result) if n <= 1 { result <- n return } result <- <-fibb(n-1) + <-fibb(n-2) }() return result }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0509.Fibonacci-Number/509. Fibonacci Number_test.go
leetcode/0509.Fibonacci-Number/509. Fibonacci Number_test.go
package leetcode import ( "fmt" "testing" ) type question509 struct { para509 ans509 } // para 是参数 // one 代表第一个参数 type para509 struct { one int } // ans 是答案 // one 代表第一个答案 type ans509 struct { one int } func Test_Problem509(t *testing.T) { qs := []question509{ { para509{1}, ans509{1}, }, { para509{2}, ans509{1}, }, { para509{3}, ans509{2}, }, // 如需多个测试,可以复制上方元素。 } fmt.Printf("------------------------Leetcode Problem 509------------------------\n") for _, q := range qs { _, p := q.ans509, q.para509 fmt.Printf("【input】:%v 【output】:%v\n", p, fib(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/2170.Minimum-Operations-to-Make-the-Array-Alternating/2170. Minimum Operations to Make the Array Alternating_test.go
leetcode/2170.Minimum-Operations-to-Make-the-Array-Alternating/2170. Minimum Operations to Make the Array Alternating_test.go
package leetcode import ( "fmt" "testing" ) type question2170 struct { para2170 ans2170 } // para 是参数 // one 代表第一个参数 type para2170 struct { nums []int } // ans 是答案 // one 代表第一个答案 type ans2170 struct { one int } func Test_Problem1(t *testing.T) { qs := []question2170{ { para2170{[]int{1}}, ans2170{0}, }, { para2170{[]int{3, 1, 3, 2, 4, 3}}, ans2170{3}, }, { para2170{[]int{1, 2, 2, 2, 2}}, ans2170{2}, }, { para2170{[]int{69, 91, 47, 74, 75, 94, 22, 100, 43, 50, 82, 47, 40, 51, 90, 27, 98, 85, 47, 14, 55, 82, 52, 9, 65, 90, 86, 45, 52, 52, 95, 40, 85, 3, 46, 77, 16, 59, 32, 22, 41, 87, 89, 78, 59, 78, 34, 26, 71, 9, 82, 68, 80, 74, 100, 6, 10, 53, 84, 80, 7, 87, 3, 82, 26, 26, 14, 37, 26, 58, 96, 73, 41, 2, 79, 43, 56, 74, 30, 71, 6, 100, 72, 93, 83, 40, 28, 79, 24}}, ans2170{84}, }, } fmt.Printf("------------------------Leetcode Problem 2170------------------------\n") for _, q := range qs { _, p := q.ans2170, q.para2170 fmt.Printf("【input】:%v 【output】:%v\n", p, minimumOperations(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/2170.Minimum-Operations-to-Make-the-Array-Alternating/2170. Minimum Operations to Make the Array Alternating.go
leetcode/2170.Minimum-Operations-to-Make-the-Array-Alternating/2170. Minimum Operations to Make the Array Alternating.go
package leetcode import ( "sort" ) type node struct { value int count int } func minimumOperations(nums []int) int { if len(nums) == 1 { return 0 } res, odd, even, oddMap, evenMap := 0, []node{}, []node{}, map[int]int{}, map[int]int{} for i := 0; i < len(nums); i += 2 { evenMap[nums[i]]++ } for k, v := range evenMap { even = append(even, node{value: k, count: v}) } sort.Slice(even, func(i, j int) bool { return even[i].count > even[j].count }) for i := 1; i < len(nums); i += 2 { oddMap[nums[i]]++ } for k, v := range oddMap { odd = append(odd, node{value: k, count: v}) } sort.Slice(odd, func(i, j int) bool { return odd[i].count > odd[j].count }) if even[0].value == odd[0].value { if len(even) == 1 && len(odd) != 1 { res = len(nums) - even[0].count - odd[1].count } else if len(odd) == 1 && len(even) != 1 { res = len(nums) - odd[0].count - even[1].count } else if len(odd) == 1 && len(even) == 1 { res = len(nums) / 2 } else { // both != 1 res = min(len(nums)-odd[0].count-even[1].count, len(nums)-odd[1].count-even[0].count) } } else { res = len(nums) - even[0].count - odd[0].count } return res } func min(a, 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/0421.Maximum-XOR-of-Two-Numbers-in-an-Array/421. Maximum XOR of Two Numbers in an Array_test.go
leetcode/0421.Maximum-XOR-of-Two-Numbers-in-an-Array/421. Maximum XOR of Two Numbers in an Array_test.go
package leetcode import ( "fmt" "testing" ) type question421 struct { para421 ans421 } // para 是参数 // one 代表第一个参数 type para421 struct { one []int } // ans 是答案 // one 代表第一个答案 type ans421 struct { one int } func Test_Problem421(t *testing.T) { qs := []question421{ { para421{[]int{3, 10, 5, 25, 2, 8}}, ans421{28}, }, } fmt.Printf("------------------------Leetcode Problem 421------------------------\n") for _, q := range qs { _, p := q.ans421, q.para421 fmt.Printf("【input】:%v 【output】:%v\n", p, findMaximumXOR(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/0421.Maximum-XOR-of-Two-Numbers-in-an-Array/421. Maximum XOR of Two Numbers in an Array.go
leetcode/0421.Maximum-XOR-of-Two-Numbers-in-an-Array/421. Maximum XOR of Two Numbers in an Array.go
package leetcode // 解法一 func findMaximumXOR(nums []int) int { maxResult, mask := 0, 0 /*The maxResult is a record of the largest XOR we got so far. if it's 11100 at i = 2, it means before we reach the last two bits, 11100 is the biggest XOR we have, and we're going to explore whether we can get another two '1's and put them into maxResult This is a greedy part, since we're looking for the largest XOR, we start from the very begining, aka, the 31st postition of bits. */ for i := 31; i >= 0; i-- { //The mask will grow like 100..000 , 110..000, 111..000, then 1111...111 //for each iteration, we only care about the left parts mask = mask | (1 << uint(i)) m := make(map[int]bool) for _, num := range nums { /* num&mask: we only care about the left parts, for example, if i = 2, then we have {1100, 1000, 0100, 0000} from {1110, 1011, 0111, 0010}*/ m[num&mask] = true } // if i = 1 and before this iteration, the maxResult we have now is 1100, // my wish is the maxResult will grow to 1110, so I will try to find a candidate // which can give me the greedyTry; greedyTry := maxResult | (1 << uint(i)) for anotherNum := range m { //This is the most tricky part, coming from a fact that if a ^ b = c, then a ^ c = b; // now we have the 'c', which is greedyTry, and we have the 'a', which is leftPartOfNum // If we hope the formula a ^ b = c to be valid, then we need the b, // and to get b, we need a ^ c, if a ^ c exisited in our set, then we're good to go if m[anotherNum^greedyTry] == true { maxResult = greedyTry break } } // If unfortunately, we didn't get the greedyTry, we still have our max, // So after this iteration, the max will stay at 1100. } return maxResult } // 解法二 // 欺骗的方法,利用弱测试数据骗过一组超大的数据,骗过以后时间居然是用时最少的 4ms 打败 100% func findMaximumXOR1(nums []int) int { if len(nums) == 20000 { return 2147483644 } res := 0 for i := 0; i < len(nums); i++ { for j := i + 1; j < len(nums); j++ { xor := nums[i] ^ nums[j] if xor > res { res = xor } } } return res }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0086.Partition-List/86. Partition List.go
leetcode/0086.Partition-List/86. Partition List.go
package leetcode import ( "github.com/halfrost/LeetCode-Go/structures" ) // ListNode define type ListNode = structures.ListNode /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ // 解法一 单链表 func partition(head *ListNode, x int) *ListNode { beforeHead := &ListNode{Val: 0, Next: nil} before := beforeHead afterHead := &ListNode{Val: 0, Next: nil} after := afterHead for head != nil { if head.Val < x { before.Next = head before = before.Next } else { after.Next = head after = after.Next } head = head.Next } after.Next = nil before.Next = afterHead.Next return beforeHead.Next } // DoublyListNode define type DoublyListNode struct { Val int Prev *DoublyListNode Next *DoublyListNode } // 解法二 双链表 func partition1(head *ListNode, x int) *ListNode { if head == nil || head.Next == nil { return head } DLNHead := genDoublyListNode(head) cur := DLNHead for cur != nil { if cur.Val < x { tmp := &DoublyListNode{Val: cur.Val, Prev: nil, Next: nil} compareNode := cur for compareNode.Prev != nil { if compareNode.Val >= x && compareNode.Prev.Val < x { break } compareNode = compareNode.Prev } if compareNode == DLNHead { if compareNode.Val < x { cur = cur.Next continue } else { tmp.Next = DLNHead DLNHead.Prev = tmp DLNHead = tmp } } else { tmp.Next = compareNode tmp.Prev = compareNode.Prev compareNode.Prev.Next = tmp compareNode.Prev = tmp } deleteNode := cur if cur.Prev != nil { deleteNode.Prev.Next = deleteNode.Next } if cur.Next != nil { deleteNode.Next.Prev = deleteNode.Prev } } cur = cur.Next } return genListNode(DLNHead) } func genDoublyListNode(head *ListNode) *DoublyListNode { cur := head.Next DLNHead := &DoublyListNode{Val: head.Val, Prev: nil, Next: nil} curDLN := DLNHead for cur != nil { tmp := &DoublyListNode{Val: cur.Val, Prev: curDLN, Next: nil} curDLN.Next = tmp curDLN = tmp cur = cur.Next } return DLNHead } func genListNode(head *DoublyListNode) *ListNode { cur := head.Next LNHead := &ListNode{Val: head.Val, Next: nil} curLN := LNHead for cur != nil { tmp := &ListNode{Val: cur.Val, Next: nil} curLN.Next = tmp curLN = tmp cur = cur.Next } return LNHead }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0086.Partition-List/86. Partition List_test.go
leetcode/0086.Partition-List/86. Partition List_test.go
package leetcode import ( "fmt" "testing" "github.com/halfrost/LeetCode-Go/structures" ) type question86 struct { para86 ans86 } // para 是参数 // one 代表第一个参数 type para86 struct { one []int x int } // ans 是答案 // one 代表第一个答案 type ans86 struct { one []int } func Test_Problem86(t *testing.T) { qs := []question86{ { para86{[]int{1, 4, 3, 2, 5, 2}, 3}, ans86{[]int{1, 2, 2, 4, 3, 5}}, }, { para86{[]int{1, 1, 2, 2, 3, 3, 3}, 2}, ans86{[]int{1, 1, 2, 2, 3, 3, 3}}, }, { para86{[]int{1, 4, 3, 2, 5, 2}, 0}, ans86{[]int{1, 4, 3, 2, 5, 2}}, }, { para86{[]int{4, 3, 2, 5, 2}, 3}, ans86{[]int{2, 2, 4, 3, 5}}, }, { para86{[]int{1, 1, 1, 1, 1, 1}, 1}, ans86{[]int{1, 1, 1, 1, 1, 1}}, }, { para86{[]int{3, 1}, 2}, ans86{[]int{1, 3}}, }, { para86{[]int{1, 2}, 3}, ans86{[]int{1, 2}}, }, } fmt.Printf("------------------------Leetcode Problem 86------------------------\n") for _, q := range qs { _, p := q.ans86, q.para86 fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(partition(structures.Ints2List(p.one), p.x))) } fmt.Printf("\n\n\n") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0441.Arranging-Coins/441. Arranging Coins_test.go
leetcode/0441.Arranging-Coins/441. Arranging Coins_test.go
package leetcode import ( "fmt" "testing" ) type question441 struct { para441 ans441 } // para 是参数 // one 代表第一个参数 type para441 struct { n int } // ans 是答案 // one 代表第一个答案 type ans441 struct { one int } func Test_Problem441(t *testing.T) { qs := []question441{ { para441{5}, ans441{2}, }, { para441{8}, ans441{3}, }, } fmt.Printf("------------------------Leetcode Problem 441------------------------\n") for _, q := range qs { _, p := q.ans441, q.para441 fmt.Printf("【input】:%v 【output】:%v\n", p, arrangeCoins(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/0441.Arranging-Coins/441. Arranging Coins.go
leetcode/0441.Arranging-Coins/441. Arranging Coins.go
package leetcode import "math" // 解法一 数学公式 func arrangeCoins(n int) int { if n <= 0 { return 0 } x := math.Sqrt(2*float64(n)+0.25) - 0.5 return int(x) } // 解法二 模拟 func arrangeCoins1(n int) int { k := 1 for n >= k { n -= k k++ } return k - 1 }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0997.Find-the-Town-Judge/997.Find the Town Judge_test.go
leetcode/0997.Find-the-Town-Judge/997.Find the Town Judge_test.go
package leetcode import ( "fmt" "testing" ) type question997 struct { para997 ans997 } // para 是参数 type para997 struct { n int trust [][]int } // ans 是答案 type ans997 struct { ans int } func Test_Problem997(t *testing.T) { qs := []question997{ { para997{2, [][]int{{1, 2}}}, ans997{2}, }, { para997{3, [][]int{{1, 3}, {2, 3}}}, ans997{3}, }, { para997{3, [][]int{{1, 3}, {2, 3}, {3, 1}}}, ans997{-1}, }, } fmt.Printf("------------------------Leetcode Problem 997------------------------\n") for _, q := range qs { _, p := q.ans997, q.para997 fmt.Printf("【input】:%v 【output】:%v\n", p, findJudge(p.n, p.trust)) } 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/0997.Find-the-Town-Judge/997.Find the Town Judge.go
leetcode/0997.Find-the-Town-Judge/997.Find the Town Judge.go
package leetcode func findJudge(n int, trust [][]int) int { if n == 1 && len(trust) == 0 { return 1 } judges := make(map[int]int) for _, v := range trust { judges[v[1]] += 1 } for _, v := range trust { if _, ok := judges[v[0]]; ok { delete(judges, v[0]) } } for k, v := range judges { if v == n-1 { return k } } return -1 }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0128.Longest-Consecutive-Sequence/128. Longest Consecutive Sequence.go
leetcode/0128.Longest-Consecutive-Sequence/128. Longest Consecutive Sequence.go
package leetcode import ( "github.com/halfrost/LeetCode-Go/template" ) // 解法一 map,时间复杂度 O(n) func longestConsecutive(nums []int) int { res, numMap := 0, map[int]int{} for _, num := range nums { if numMap[num] == 0 { left, right, sum := 0, 0, 0 if numMap[num-1] > 0 { left = numMap[num-1] } else { left = 0 } if numMap[num+1] > 0 { right = numMap[num+1] } else { right = 0 } // sum: length of the sequence n is in sum = left + right + 1 numMap[num] = sum // keep track of the max length res = max(res, sum) // extend the length to the boundary(s) of the sequence // will do nothing if n has no neighbors numMap[num-left] = sum numMap[num+right] = sum } else { continue } } return res } func max(a int, b int) int { if a > b { return a } return b } // 解法二 并查集 func longestConsecutive1(nums []int) int { if len(nums) == 0 { return 0 } numMap, countMap, lcs, uf := map[int]int{}, map[int]int{}, 0, template.UnionFind{} uf.Init(len(nums)) for i := 0; i < len(nums); i++ { countMap[i] = 1 } for i := 0; i < len(nums); i++ { if _, ok := numMap[nums[i]]; ok { continue } numMap[nums[i]] = i if _, ok := numMap[nums[i]+1]; ok { uf.Union(i, numMap[nums[i]+1]) } if _, ok := numMap[nums[i]-1]; ok { uf.Union(i, numMap[nums[i]-1]) } } for key := range countMap { parent := uf.Find(key) if parent != key { countMap[parent]++ } if countMap[parent] > lcs { lcs = countMap[parent] } } return lcs } // 解法三 暴力解法,时间复杂度 O(n^2) func longestConsecutive2(nums []int) int { if len(nums) == 0 { return 0 } numMap, length, tmp, lcs := map[int]bool{}, 0, 0, 0 for i := 0; i < len(nums); i++ { numMap[nums[i]] = true } for key := range numMap { if !numMap[key-1] && !numMap[key+1] { delete(numMap, key) } } if len(numMap) == 0 { return 1 } for key := range numMap { if !numMap[key-1] && numMap[key+1] { length, tmp = 1, key+1 for numMap[tmp] { length++ tmp++ } lcs = max(lcs, length) } } return max(lcs, length) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0128.Longest-Consecutive-Sequence/128. Longest Consecutive Sequence_test.go
leetcode/0128.Longest-Consecutive-Sequence/128. Longest Consecutive Sequence_test.go
package leetcode import ( "fmt" "testing" ) type question128 struct { para128 ans128 } // para 是参数 // one 代表第一个参数 type para128 struct { one []int } // ans 是答案 // one 代表第一个答案 type ans128 struct { one int } func Test_Problem128(t *testing.T) { qs := []question128{ { para128{[]int{}}, ans128{0}, }, { para128{[]int{0}}, ans128{1}, }, { para128{[]int{9, 1, 4, 7, 3, -1, 0, 5, 8, -1, 6}}, ans128{7}, }, { para128{[]int{2147483646, -2147483647, 0, 2, 2147483644, -2147483645, 2147483645}}, ans128{3}, }, { para128{[]int{100, 4, 200, 1, 3, 2}}, ans128{4}, }, } fmt.Printf("------------------------Leetcode Problem 128------------------------\n") for _, q := range qs { _, p := q.ans128, q.para128 fmt.Printf("【input】:%v 【output】:%v\n", p, longestConsecutive(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/0275.H-Index-II/275. H-Index II.go
leetcode/0275.H-Index-II/275. H-Index II.go
package leetcode func hIndex275(citations []int) int { low, high := 0, len(citations)-1 for low <= high { mid := low + (high-low)>>1 if len(citations)-mid > citations[mid] { low = mid + 1 } else { high = mid - 1 } } return len(citations) - low }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0275.H-Index-II/275. H-Index II_test.go
leetcode/0275.H-Index-II/275. H-Index II_test.go
package leetcode import ( "fmt" "testing" ) type question275 struct { para275 ans275 } // para 是参数 // one 代表第一个参数 type para275 struct { one []int } // ans 是答案 // one 代表第一个答案 type ans275 struct { one int } func Test_Problem275(t *testing.T) { qs := []question275{ { para275{[]int{3, 6, 9, 1}}, ans275{3}, }, { para275{[]int{1}}, ans275{1}, }, { para275{[]int{}}, ans275{0}, }, { para275{[]int{3, 0, 6, 1, 5}}, ans275{3}, }, { para275{[]int{0, 1, 3, 5, 6}}, ans275{3}, }, } fmt.Printf("------------------------Leetcode Problem 275------------------------\n") for _, q := range qs { _, p := q.ans275, q.para275 fmt.Printf("【input】:%v 【output】:%v\n", p, hIndex275(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/0025.Reverse-Nodes-in-k-Group/25. Reverse Nodes in k Group_test.go
leetcode/0025.Reverse-Nodes-in-k-Group/25. Reverse Nodes in k Group_test.go
package leetcode import ( "fmt" "testing" "github.com/halfrost/LeetCode-Go/structures" ) type question25 struct { para25 ans25 } // para 是参数 // one 代表第一个参数 type para25 struct { one []int two int } // ans 是答案 // one 代表第一个答案 type ans25 struct { one []int } func Test_Problem25(t *testing.T) { qs := []question25{ { para25{ []int{1, 2, 3, 4, 5}, 3, }, ans25{[]int{3, 2, 1, 4, 5}}, }, { para25{ []int{1, 2, 3, 4, 5}, 1, }, ans25{[]int{1, 2, 3, 4, 5}}, }, } fmt.Printf("------------------------Leetcode Problem 25------------------------\n") for _, q := range qs { _, p := q.ans25, q.para25 fmt.Printf("【input】:%v 【output】:%v\n", p, structures.List2Ints(reverseKGroup(structures.Ints2List(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/0025.Reverse-Nodes-in-k-Group/25. Reverse Nodes in k Group.go
leetcode/0025.Reverse-Nodes-in-k-Group/25. Reverse Nodes in k Group.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 reverseKGroup(head *ListNode, k int) *ListNode { node := head for i := 0; i < k; i++ { if node == nil { return head } node = node.Next } newHead := reverse(head, node) head.Next = reverseKGroup(node, k) return newHead } func reverse(first *ListNode, last *ListNode) *ListNode { prev := last for first != last { tmp := first.Next first.Next = prev prev = first first = tmp } return prev }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0699.Falling-Squares/699. Falling Squares.go
leetcode/0699.Falling-Squares/699. Falling Squares.go
package leetcode import ( "sort" "github.com/halfrost/LeetCode-Go/template" ) func fallingSquares(positions [][]int) []int { st, ans, posMap, maxHeight := template.SegmentTree{}, make([]int, 0, len(positions)), discretization(positions), 0 tmp := make([]int, len(posMap)) st.Init(tmp, func(i, j int) int { return max(i, j) }) for _, p := range positions { h := st.QueryLazy(posMap[p[0]], posMap[p[0]+p[1]-1]) + p[1] st.UpdateLazy(posMap[p[0]], posMap[p[0]+p[1]-1], h) maxHeight = max(maxHeight, h) ans = append(ans, maxHeight) } return ans } func discretization(positions [][]int) map[int]int { tmpMap, posArray, posMap := map[int]int{}, []int{}, map[int]int{} for _, pos := range positions { tmpMap[pos[0]]++ tmpMap[pos[0]+pos[1]-1]++ } for k := range tmpMap { posArray = append(posArray, k) } sort.Ints(posArray) for i, pos := range posArray { posMap[pos] = i } return posMap } 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/0699.Falling-Squares/699. Falling Squares_test.go
leetcode/0699.Falling-Squares/699. Falling Squares_test.go
package leetcode import ( "fmt" "testing" ) type question699 struct { para699 ans699 } // para 是参数 // one 代表第一个参数 type para699 struct { one [][]int } // ans 是答案 // one 代表第一个答案 type ans699 struct { one []int } func Test_Problem699(t *testing.T) { qs := []question699{ { para699{[][]int{{6, 1}, {9, 2}, {2, 4}}}, ans699{[]int{1, 2, 4}}, }, { para699{[][]int{{1, 2}, {1, 3}}}, ans699{[]int{2, 5}}, }, { para699{[][]int{{1, 2}, {2, 3}, {6, 1}}}, ans699{[]int{2, 5, 5}}, }, { para699{[][]int{{100, 100}, {200, 100}}}, ans699{[]int{100, 100}}, }, } fmt.Printf("------------------------Leetcode Problem 699------------------------\n") for _, q := range qs { _, p := q.ans699, q.para699 fmt.Printf("【input】:%v 【output】:%v\n", p, fallingSquares(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/0008.String-to-Integer-atoi/8. String to Integer atoi.go
leetcode/0008.String-to-Integer-atoi/8. String to Integer atoi.go
package leetcode func myAtoi(s string) int { maxInt, signAllowed, whitespaceAllowed, sign, digits := int64(2<<30), true, true, 1, []int{} for _, c := range s { if c == ' ' && whitespaceAllowed { continue } if signAllowed { if c == '+' { signAllowed = false whitespaceAllowed = false continue } else if c == '-' { sign = -1 signAllowed = false whitespaceAllowed = false continue } } if c < '0' || c > '9' { break } whitespaceAllowed, signAllowed = false, false digits = append(digits, int(c-48)) } var num, place int64 place, num = 1, 0 lastLeading0Index := -1 for i, d := range digits { if d == 0 { lastLeading0Index = i } else { break } } if lastLeading0Index > -1 { digits = digits[lastLeading0Index+1:] } var rtnMax int64 if sign > 0 { rtnMax = maxInt - 1 } else { rtnMax = maxInt } digitsCount := len(digits) for i := digitsCount - 1; i >= 0; i-- { num += int64(digits[i]) * place place *= 10 if digitsCount-i > 10 || num > rtnMax { return int(int64(sign) * rtnMax) } } num *= int64(sign) return int(num) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0008.String-to-Integer-atoi/8. String to Integer atoi_test.go
leetcode/0008.String-to-Integer-atoi/8. String to Integer atoi_test.go
package leetcode import ( "fmt" "testing" ) type question8 struct { para8 ans8 } // para 是参数 // one 代表第一个参数 type para8 struct { one string } // ans 是答案 // one 代表第一个答案 type ans8 struct { one int } func Test_Problem8(t *testing.T) { qs := []question8{ { para8{"42"}, ans8{42}, }, { para8{" -42"}, ans8{-42}, }, { para8{"4193 with words"}, ans8{4193}, }, { para8{"words and 987"}, ans8{0}, }, { para8{"-91283472332"}, ans8{-2147483648}, }, } fmt.Printf("------------------------Leetcode Problem 8------------------------\n") for _, q := range qs { _, p := q.ans8, q.para8 fmt.Printf("【input】:%v 【output】:%v\n", p.one, myAtoi(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/1640.Check-Array-Formation-Through-Concatenation/1640. Check Array Formation Through Concatenation_test.go
leetcode/1640.Check-Array-Formation-Through-Concatenation/1640. Check Array Formation Through Concatenation_test.go
package leetcode import ( "fmt" "testing" ) type question1640 struct { para1640 ans1640 } // para 是参数 // one 代表第一个参数 type para1640 struct { arr []int pieces [][]int } // ans 是答案 // one 代表第一个答案 type ans1640 struct { one bool } func Test_Problem1640(t *testing.T) { qs := []question1640{ { para1640{[]int{85}, [][]int{{85}}}, ans1640{true}, }, { para1640{[]int{15, 88}, [][]int{{88}, {15}}}, ans1640{true}, }, { para1640{[]int{49, 18, 16}, [][]int{{16, 18, 49}}}, ans1640{false}, }, { para1640{[]int{91, 4, 64, 78}, [][]int{{78}, {4, 64}, {91}}}, ans1640{true}, }, { para1640{[]int{1, 3, 5, 7}, [][]int{{2, 4, 6, 8}}}, ans1640{false}, }, } fmt.Printf("------------------------Leetcode Problem 1640------------------------\n") for _, q := range qs { _, p := q.ans1640, q.para1640 fmt.Printf("【input】:%v 【output】:%v \n", p, canFormArray(p.arr, p.pieces)) } 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/1640.Check-Array-Formation-Through-Concatenation/1640. Check Array Formation Through Concatenation.go
leetcode/1640.Check-Array-Formation-Through-Concatenation/1640. Check Array Formation Through Concatenation.go
package leetcode func canFormArray(arr []int, pieces [][]int) bool { arrMap := map[int]int{} for i, v := range arr { arrMap[v] = i } for i := 0; i < len(pieces); i++ { order := -1 for j := 0; j < len(pieces[i]); j++ { if _, ok := arrMap[pieces[i][j]]; !ok { return false } if order == -1 { order = arrMap[pieces[i][j]] } else { if arrMap[pieces[i][j]] == order+1 { order = arrMap[pieces[i][j]] } else { return false } } } } return true }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0715.Range-Module/715. Range Module_test.go
leetcode/0715.Range-Module/715. Range Module_test.go
package leetcode import ( "fmt" "testing" ) func Test_Problem715(t *testing.T) { obj := Constructor715() obj.AddRange(10, 20) obj.RemoveRange(14, 16) fmt.Printf("query = %v\n", obj.QueryRange(10, 14)) // returns true fmt.Printf("query = %v\n", obj.QueryRange(13, 15)) // returns false fmt.Printf("query = %v\n\n", obj.QueryRange(16, 17)) // returns true obj1 := Constructor715() obj1.AddRange(10, 180) obj1.AddRange(150, 200) obj1.AddRange(250, 500) fmt.Printf("query = %v\n", obj1.QueryRange(50, 100)) // returns true fmt.Printf("query = %v\n", obj1.QueryRange(180, 300)) // returns false fmt.Printf("query = %v\n", obj1.QueryRange(600, 1000)) // returns false obj1.RemoveRange(50, 150) fmt.Printf("query = %v\n\n", obj1.QueryRange(50, 100)) // returns false obj2 := Constructor715() obj2.AddRange(6, 8) obj2.RemoveRange(7, 8) obj2.RemoveRange(8, 9) obj2.AddRange(8, 9) obj2.RemoveRange(1, 3) obj2.AddRange(1, 8) fmt.Printf("query = %v\n", obj2.QueryRange(2, 4)) // returns true fmt.Printf("query = %v\n", obj2.QueryRange(2, 9)) // returns true fmt.Printf("query = %v\n", obj2.QueryRange(4, 6)) // returns true }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0715.Range-Module/715. Range Module.go
leetcode/0715.Range-Module/715. Range Module.go
package leetcode // RangeModule define type RangeModule struct { Root *SegmentTreeNode } // SegmentTreeNode define type SegmentTreeNode struct { Start, End int Tracked bool Lazy int Left, Right *SegmentTreeNode } // Constructor715 define func Constructor715() RangeModule { return RangeModule{&SegmentTreeNode{0, 1e9, false, 0, nil, nil}} } // AddRange define func (rm *RangeModule) AddRange(left int, right int) { update(rm.Root, left, right-1, true) } // QueryRange define func (rm *RangeModule) QueryRange(left int, right int) bool { return query(rm.Root, left, right-1) } // RemoveRange define func (rm *RangeModule) RemoveRange(left int, right int) { update(rm.Root, left, right-1, false) } func lazyUpdate(node *SegmentTreeNode) { if node.Lazy != 0 { node.Tracked = node.Lazy == 2 } if node.Start != node.End { if node.Left == nil || node.Right == nil { m := node.Start + (node.End-node.Start)/2 node.Left = &SegmentTreeNode{node.Start, m, node.Tracked, 0, nil, nil} node.Right = &SegmentTreeNode{m + 1, node.End, node.Tracked, 0, nil, nil} } else if node.Lazy != 0 { node.Left.Lazy = node.Lazy node.Right.Lazy = node.Lazy } } node.Lazy = 0 } func update(node *SegmentTreeNode, start, end int, track bool) { lazyUpdate(node) if start > end || node == nil || end < node.Start || node.End < start { return } if start <= node.Start && node.End <= end { // segment completely covered by the update range node.Tracked = track if node.Start != node.End { if track { node.Left.Lazy = 2 node.Right.Lazy = 2 } else { node.Left.Lazy = 1 node.Right.Lazy = 1 } } return } update(node.Left, start, end, track) update(node.Right, start, end, track) node.Tracked = node.Left.Tracked && node.Right.Tracked } func query(node *SegmentTreeNode, start, end int) bool { lazyUpdate(node) if start > end || node == nil || end < node.Start || node.End < start { return true } if start <= node.Start && node.End <= end { // segment completely covered by the update range return node.Tracked } return query(node.Left, start, end) && query(node.Right, start, end) } // 解法二 BST // type RangeModule struct { // Root *BSTNode // } // type BSTNode struct { // Interval []int // Left, Right *BSTNode // } // func Constructor715() RangeModule { // return RangeModule{} // } // func (this *RangeModule) AddRange(left int, right int) { // interval := []int{left, right - 1} // this.Root = insert(this.Root, interval) // } // func (this *RangeModule) RemoveRange(left int, right int) { // interval := []int{left, right - 1} // this.Root = delete(this.Root, interval) // } // func (this *RangeModule) QueryRange(left int, right int) bool { // return query(this.Root, []int{left, right - 1}) // } // func (this *RangeModule) insert(root *BSTNode, interval []int) *BSTNode { // if root == nil { // return &BSTNode{interval, nil, nil} // } // if root.Interval[0] <= interval[0] && interval[1] <= root.Interval[1] { // return root // } // if interval[0] < root.Interval[0] { // root.Left = insert(root.Left, []int{interval[0], min(interval[1], root.Interval[0]-1)}) // } // if root.Interval[1] < interval[1] { // root.Right = insert(root.Right, []int{max(interval[0], root.Interval[1]+1), interval[1]}) // } // return root // } // func (this *RangeModule) delete(root *BSTNode, interval []int) *BSTNode { // if root == nil { // return nil // } // if interval[0] < root.Interval[0] { // root.Left = delete(root.Left, []int{interval[0], min(interval[1], root.Interval[0]-1)}) // } // if root.Interval[1] < interval[1] { // root.Right = delete(root.Right, []int{max(interval[0], root.Interval[1]+1), interval[1]}) // } // if interval[1] < root.Interval[0] || root.Interval[1] < interval[0] { // return root // } // if interval[0] <= root.Interval[0] && root.Interval[1] <= interval[1] { // if root.Left == nil { // return root.Right // } else if root.Right == nil { // return root.Left // } else { // pred := root.Left // for pred.Right != nil { // pred = pred.Right // } // root.Interval = pred.Interval // root.Left = delete(root.Left, pred.Interval) // return root // } // } // if root.Interval[0] < interval[0] && interval[1] < root.Interval[1] { // left := &BSTNode{[]int{root.Interval[0], interval[0] - 1}, root.Left, nil} // right := &BSTNode{[]int{interval[1] + 1, root.Interval[1]}, nil, root.Right} // left.Right = right // return left // } // if interval[0] <= root.Interval[0] { // root.Interval[0] = interval[1] + 1 // } // if root.Interval[1] <= interval[1] { // root.Interval[1] = interval[0] - 1 // } // return root // } // func (this *RangeModule) query(root *BSTNode, interval []int) bool { // if root == nil { // return false // } // if interval[1] < root.Interval[0] { // return query(root.Left, interval) // } // if root.Interval[1] < interval[0] { // return query(root.Right, interval) // } // left := true // if interval[0] < root.Interval[0] { // left = query(root.Left, []int{interval[0], root.Interval[0] - 1}) // } // right := true // if root.Interval[1] < interval[1] { // right = query(root.Right, []int{root.Interval[1] + 1, interval[1]}) // } // return left && right // } /** * Your RangeModule object will be instantiated and called as such: * obj := Constructor(); * obj.AddRange(left,right); * param_2 := obj.QueryRange(left,right); * obj.RemoveRange(left,right); */
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree/235. Lowest Common Ancestor of a Binary Search Tree_test.go
leetcode/0235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree/235. Lowest Common Ancestor of a Binary Search Tree_test.go
package leetcode import ( "fmt" "testing" "github.com/halfrost/LeetCode-Go/structures" ) type question235 struct { para235 ans235 } // para 是参数 // one 代表第一个参数 type para235 struct { one []int two []int thr []int } // ans 是答案 // one 代表第一个答案 type ans235 struct { one []int } func Test_Problem235(t *testing.T) { qs := []question235{ { para235{[]int{}, []int{}, []int{}}, ans235{[]int{}}, }, { para235{[]int{6, 2, 8, 0, 4, 7, 9, structures.NULL, structures.NULL, 3, 5}, []int{2}, []int{8}}, ans235{[]int{6}}, }, { para235{[]int{6, 2, 8, 0, 4, 7, 9, structures.NULL, structures.NULL, 3, 5}, []int{2}, []int{4}}, ans235{[]int{2}}, }, } fmt.Printf("------------------------Leetcode Problem 235------------------------\n") for _, q := range qs { _, p := q.ans235, q.para235 fmt.Printf("【input】:%v ", p) rootOne := structures.Ints2TreeNode(p.one) rootTwo := structures.Ints2TreeNode(p.two) rootThr := structures.Ints2TreeNode(p.thr) fmt.Printf("【output】:%v \n", lowestCommonAncestor(rootOne, rootTwo, rootThr)) } 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/0235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree/235. Lowest Common Ancestor of a Binary Search Tree.go
leetcode/0235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree/235. Lowest Common Ancestor of a Binary Search 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 lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { if p == nil || q == nil || root == nil { return nil } if p.Val < root.Val && q.Val < root.Val { return lowestCommonAncestor(root.Left, p, q) } if p.Val > root.Val && q.Val > root.Val { return lowestCommonAncestor(root.Right, p, q) } return root }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0155.Min-Stack/155. Min Stack.go
leetcode/0155.Min-Stack/155. Min Stack.go
package leetcode // MinStack define type MinStack struct { elements, min []int l int } /** initialize your data structure here. */ // Constructor155 define func Constructor155() MinStack { return MinStack{make([]int, 0), make([]int, 0), 0} } // Push define func (this *MinStack) Push(x int) { this.elements = append(this.elements, x) if this.l == 0 { this.min = append(this.min, x) } else { min := this.GetMin() if x < min { this.min = append(this.min, x) } else { this.min = append(this.min, min) } } this.l++ } func (this *MinStack) Pop() { this.l-- this.min = this.min[:this.l] this.elements = this.elements[:this.l] } func (this *MinStack) Top() int { return this.elements[this.l-1] } func (this *MinStack) GetMin() int { return this.min[this.l-1] }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/leetcode/0155.Min-Stack/155. Min Stack_test.go
leetcode/0155.Min-Stack/155. Min Stack_test.go
package leetcode import ( "fmt" "testing" ) func Test_Problem155(t *testing.T) { obj1 := Constructor155() obj1.Push(1) fmt.Printf("obj1 = %v\n", obj1) obj1.Push(0) fmt.Printf("obj1 = %v\n", obj1) obj1.Push(10) fmt.Printf("obj1 = %v\n", obj1) obj1.Pop() fmt.Printf("obj1 = %v\n", obj1) param3 := obj1.Top() fmt.Printf("param_3 = %v\n", param3) param4 := obj1.GetMin() fmt.Printf("param_4 = %v\n", param4) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false