Go 刷题技巧
# Go 数据类型
# 栈
// 创建栈
stack:=make([]int,0)
// push压入
stack=append(stack,10)
// pop弹出
v:=stack[len(stack)-1]
stack=stack[:len(stack)-1]
// 检查栈空
len(stack)==0
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 队列
// 创建队列
queue:=make([]int,0)
// enqueue入队
queue=append(queue,10)
// dequeue出队
v:=queue[0]
queue=queue[1:]
// 长度0为空
len(queue)==0
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 深拷贝
在回溯中经常需要添加路径等信息,当数组中添加切片的时候,需要注意对切片深拷贝
ans = append(ans, path) // 错误做法
// 正确做法
tmp = make([]int, len(path))
copy(tmp, path)
ans = append(ans, tmp)
1
2
3
4
5
6
2
3
4
5
6
# Go 排序
基础排序
// int排序
sort.Ints([]int{})
// 字符串排序
sort.Strings([]string{})
1
2
3
4
2
3
4
自定义排序,
sort.Slice(s, func(i,j int) bool {return s[i]<s[j]})
// 第一个元素正排,第二个元素倒排
sort.Slice(nums, func(i, j int) bool {
if nums[i][0] == nums[j][0] {
return nums[i][1] > nums[j][1] // 倒排
}
return nums[i][0] < nums[j][0] // 正排
})
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# Go min/max 函数
整数最大最小值
// int32 最大最小值
math.MaxInt32 // 实际值:1<<31-1
math.MinInt32 // 实际值:-1<<31
// int64 最大最小值(int默认是int64)
math.MaxInt64
math.MinInt64
1
2
3
4
5
6
2
3
4
5
6
简单 min/max 实现
func min (a, b int) int {
if a > b {
return b
}
return a
}
1
2
3
4
5
6
2
3
4
5
6
不定参数的 min/max 实现
func min (nums ...int) {
minValue = math.MaxInt64
for _, num := nums {
if num < minValue {
minValue = num
}
}
return minValue
}
// 调用
min(3, 4, 2, 7)
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# Go 字典记忆化搜索
// 自定义类型 Key 作为map函数的 key
type Key struct {
i int
j int
}
func ProblemXX(a string, b string) int {
var cache = map[Key]int // 定义变量
cache = make(map[Key]int) // 初始化
}
// 使用
v, ok = cache[Key{1, 2}]
if ok {
...
} else {
...
}
// 设置新 Key
cache[Key{1, 2}] = 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Go 字符串操作
Go 修改某个字符串的值
// 错误做法
s:= "abcd"
s[1] = "c"
// 正确做法
sArr := strings.Split(s, "") // abcd -> ["a", "b", "c", "d"]
sArr[1] = "c" // 修改 ["a", "c", "c", "d"]
s = strings.Join(sArr, "") ["a", "c", "c", "d"] -> "accd"
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Go 字符和数字转换
strconv.Atoi(string) // 字符串 -> 数字
strconv.Iota(int) // 数字 -> 字符串
string(97) // int -> string
string('a') // rune -> string
1
2
3
4
2
3
4
Go 字符遍历
// 按 ascii 字符遍历, 类型是 rune, 相当于 int32
theme := "狙击 start"
for i := 0; i < len(theme); i++ {
fmt.Printf("ascii: %c %d\n", theme[i], theme[i])
}
// 按 unicode 字符遍历, 相当于 int32
for _, s := range theme {
fmt.Printf("Unicode: %c %d\n", s, s)
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
编辑 (opens new window)
上次更新: 2022/10/25, 02:40:54