Golang 常用函数

数学函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

反转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func reverseString(s string) string {
	runes := []rune(s)
	length := len(runes)
	for i, j := 0, length-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func reverse(slice []int) {
	for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
		slice[i], slice[j] = slice[j], slice[i]
	}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
type InitHeap []int

func (hp InitHeap) Len() int           { return len(hp) }
func (hp InitHeap) Less(i, j int) bool { return hp[i] < hp[j] }
func (hp InitHeap) Swap(i, j int)      { hp[i], hp[j] = hp[j], hp[i] }
func (hp *InitHeap) Push(x interface{}) {
	*hp = append(*hp, x.(int))
}
func (hp *InitHeap) Pop() interface{} {
	old := *hp
	n := len(old)
	x := old[n-1]
	*hp = old[:n-1]
	return x
}

链表和树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

type ListNode struct {
	Val  int
	Next *ListNode
}

type Node struct {
	Val      int
	Children []*Node
}
本文作者:
本文链接: https://hgnulb.github.io/blog/10823806
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!