这是一个知识汇总任务,不涉及代码实现,直接给你整理。
LeetCode Go 常用函数速查表
一、数学函数 math
go
import "math"
math.Max(float64(a), float64(b)) // 最大值(需转 float64)
math.Min(float64(a), float64(b)) // 最小值
math.Abs(float64(a)) // 绝对值
math.Sqrt(float64(a)) // 平方根
math.Pow(base, exp) // 幂运算
math.Log(x) // 自然对数
math.Log2(x) // 以2为底
math.Log10(x) // 以10为底
math.Floor(x) // 向下取整
math.Ceil(x) // 向上取整
math.Inf(1) // +∞
math.Inf(-1) // -∞
math.IsInf(x, 1) // 是否为+∞
math.MaxInt64 // int64 最大值
math.MinInt64 // int64 最小值(实际用 -1<<63)
整数 max/min(Go 1.21+):
go
max(a, b) // 内置,不需要 import
min(a, b)
二、排序 sort
go
import "sort"
// 排序 int slice
sort.Ints(nums)
sort.Sort(sort.Reverse(sort.IntSlice(nums))) // 降序
// 排序 string slice
sort.Strings(strs)
// 自定义排序
sort.Slice(nums, func(i, j int) bool {
return nums[i] < nums[j]
})
// 稳定排序
sort.SliceStable(nums, func(i, j int) bool {
return nums[i] < nums[j]
})
// 二分查找(返回第一个 >= target 的下标)
idx := sort.SearchInts(nums, target)
// 通用二分
idx := sort.Search(len(nums), func(i int) bool {
return nums[i] >= target
})
// 判断是否已排序
sort.IntsAreSorted(nums)
三、字符串 strings / strconv
go
import "strings"
strings.Contains(s, sub) // 包含子串
strings.HasPrefix(s, prefix) // 前缀
strings.HasSuffix(s, suffix) // 后缀
strings.Index(s, sub) // 第一次出现位置,-1表示不存在
strings.LastIndex(s, sub) // 最后一次出现
strings.Count(s, sub) // 出现次数
strings.Replace(s, old, new, n) // 替换 n 次,-1全替换
strings.ReplaceAll(s, old, new) // 全替换
strings.ToLower(s) // 转小写
strings.ToUpper(s) // 转大写
strings.TrimSpace(s) // 去首尾空格
strings.Trim(s, cutset) // 去首尾指定字符
strings.TrimLeft / TrimRight // 去左/右侧
strings.Split(s, sep) // 分割 -> []string
strings.Join(strs, sep) // 合并
strings.Repeat(s, n) // 重复n次
strings.Fields(s) // 按空白分割(自动处理多个空格)
strings.EqualFold(s, t) // 忽略大小写比较
// 字符串构建(高性能)
var sb strings.Builder
sb.WriteString("hello")
sb.WriteByte('!')
sb.WriteRune('中')
result := sb.String()
go
import "strconv"
strconv.Atoi("123") // string -> int,返回 (int, error)
strconv.Itoa(123) // int -> string
strconv.ParseInt("ff", 16, 64) // 解析16进制
strconv.FormatInt(255, 16) // int64 -> 16进制字符串
strconv.ParseFloat("3.14", 64) // string -> float64
strconv.FormatFloat(3.14, 'f', 2, 64)
四、Slice 常用操作
go
// 追加
nums = append(nums, 1)
nums = append(nums, slice2...) // 合并两个 slice
// 删除下标 i 的元素(保序)
nums = append(nums[:i], nums[i+1:]...)
// 删除下标 i 的元素(不保序,O(1))
nums[i] = nums[len(nums)-1]
nums = nums[:len(nums)-1]
// 插入
nums = append(nums[:i+1], nums[i:]...)
nums[i] = val
// 复制
dst := make([]int, len(src))
copy(dst, src)
// 反转
for i, j := 0, len(nums)-1; i < j; i, j = i+1, j-1 {
nums[i], nums[j] = nums[j], nums[i]
}
// 二维数组初始化
grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
}
五、Map 常用操作
go
// 初始化
m := make(map[string]int)
m := map[string]int{"a": 1}
// 读取(带默认值)
v := m["key"] // 不存在返回零值
v, ok := m["key"] // ok=false 表示不存在
// 删除
delete(m, "key")
// 遍历
for k, v := range m { }
// 统计词频
freq := make(map[byte]int)
for _, c := range s {
freq[c]++
}
六、栈 / 队列(用 slice 模拟)
go
// 栈
stack := []int{}
stack = append(stack, val) // push
top := stack[len(stack)-1] // peek
stack = stack[:len(stack)-1] // pop
// 队列
queue := []int{}
queue = append(queue, val) // enqueue
front := queue[0] // peek
queue = queue[1:] // dequeue(大量使用时性能差)
七、堆 container/heap
go
import "container/heap"
// 最小堆
type MinHeap []int
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *MinHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[:n-1]
return x
}
h := &MinHeap{3, 1, 2}
heap.Init(h)
heap.Push(h, 0)
top := (*h)[0] // 堆顶(不弹出)
val := heap.Pop(h).(int)
八、位运算
go
x & y // AND
x | y // OR
x ^ y // XOR(两数相同位不同则为1)
x ^ x == 0 // 自身异或为0(找只出现一次的数)
x &^ y // AND NOT(清除 y 中为1的位)
x << n // 左移
x >> n // 右移
x & 1 // 判断奇偶(1=奇,0=偶)
x & (x-1) // 消去最低位的1(判断2的幂:x&(x-1)==0)
x & (-x) // 取最低位的1(lowbit)
bits.OnesCount(uint(x)) // 统计1的个数(import "math/bits")
bits.Len(uint(x)) // 最高位位置
九、常用数据结构手写模板
go
// 链表节点
type ListNode struct {
Val int
Next *ListNode
}
// 树节点
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
十、fmt 格式化(不常用但偶尔要)
go
import "fmt"
fmt.Sprintf("%d", 42) // int -> string
fmt.Sprintf("%05d", 42) // 补零
fmt.Sprintf("%b", 42) // 二进制
fmt.Sprintf("%x", 42) // 十六进制
十一、常用 int 操作
go
// 绝对值(int,不用 math.Abs)
func abs(x int) int {
if x < 0 { return -x }
return x
}
// 最大公约数
func gcd(a, b int) int {
for b != 0 { a, b = b, a%b }
return a
}
// 最小公倍数
func lcm(a, b int) int { return a / gcd(a, b) * b }
这些覆盖了 LeetCode Go 刷题 95% 的场景。需要某个部分展开更多例子吗?