Add build script for Go and update Go codes.

This commit is contained in:
krahets
2023-02-09 04:45:06 +08:00
parent 12c085a088
commit e8c78f89f0
39 changed files with 391 additions and 1468 deletions

View File

@ -5,7 +5,6 @@
package chapter_computational_complexity
import (
"fmt"
"math/rand"
)
@ -34,14 +33,3 @@ func findOne(nums []int) int {
}
return -1
}
/* Driver Code */
func main() {
for i := 0; i < 10; i++ {
n := 100
nums := randomNumbers(n)
index := findOne(nums)
fmt.Println("\n数组 [ 1, 2, ..., n ] 被打乱后 =", nums)
fmt.Println("数字 1 的索引为", index)
}
}

View File

@ -14,7 +14,7 @@ func TestWorstBestTimeComplexity(t *testing.T) {
n := 100
nums := randomNumbers(n)
index := findOne(nums)
fmt.Println("打乱后的数组为", nums)
fmt.Println("\n数组 [ 1, 2, ..., n ] 被打乱后 =", nums)
fmt.Println("数字 1 的索引为", index)
}
}

View File

@ -17,6 +17,7 @@ type arrayHashMap struct {
bucket []*entry
}
/* 初始化哈希表 */
func newArrayHashMap() *arrayHashMap {
// 初始化一个长度为 100 的桶(数组)
bucket := make([]*entry, 100)

View File

@ -25,7 +25,7 @@ func linearSearchArray(nums []int, target int) int {
func linearSearchLinkedList(node *ListNode, target int) *ListNode {
// 遍历链表
for node != nil {
// 找到目标元素,返回其索引
// 找到目标结点,返回
if node.Val == target {
return node
}

View File

@ -4,6 +4,7 @@
package chapter_sorting
/* 插入排序 */
func insertionSort(nums []int) {
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i := 1; i < len(nums); i++ {

View File

@ -4,7 +4,7 @@
package chapter_sorting
// 合并左子数组和右子数组
/* 合并左子数组和右子数组 */
// 左子数组区间 [left, mid]
// 右子数组区间 [mid + 1, right]
func merge(nums []int, left, mid, right int) {
@ -37,6 +37,7 @@ func merge(nums []int, left, mid, right int) {
}
}
/* 归并排序 */
func mergeSort(nums []int, left, right int) {
// 终止条件
if left >= right {

View File

@ -12,7 +12,7 @@ type arrayQueue struct {
queCapacity int // 队列容量(即最大容纳元素数量)
}
// newArrayQueue 基于环形数组实现的队列
/* 初始化队列 */
func newArrayQueue(queCapacity int) *arrayQueue {
return &arrayQueue{
nums: make([]int, queCapacity),
@ -22,17 +22,17 @@ func newArrayQueue(queCapacity int) *arrayQueue {
}
}
// size 获取队列的长度
/* 获取队列的长度 */
func (q *arrayQueue) size() int {
return q.queSize
}
// isEmpty 判断队列是否为空
/* 判断队列是否为空 */
func (q *arrayQueue) isEmpty() bool {
return q.queSize == 0
}
// push 入队
/* 入队 */
func (q *arrayQueue) push(num int) {
// 当 rear == queCapacity 表示队列已满
if q.queSize == q.queCapacity {
@ -46,7 +46,7 @@ func (q *arrayQueue) push(num int) {
q.queSize++
}
// poll 出队
/* 出队 */
func (q *arrayQueue) poll() any {
num := q.peek()
// 队首指针向后移动一位,若越过尾部则返回到数组头部
@ -55,7 +55,7 @@ func (q *arrayQueue) poll() any {
return num
}
// peek 访问队首元素
/* 访问队首元素 */
func (q *arrayQueue) peek() any {
if q.isEmpty() {
return nil
@ -63,7 +63,7 @@ func (q *arrayQueue) peek() any {
return q.nums[q.front]
}
// 获取 Slice 用于打印
/* 获取 Slice 用于打印 */
func (q *arrayQueue) toSlice() []int {
rear := (q.front + q.queSize)
if rear >= q.queCapacity {

View File

@ -9,6 +9,7 @@ type arrayStack struct {
data []int // 数据
}
/* 初始化栈 */
func newArrayStack() *arrayStack {
return &arrayStack{
// 设置栈的长度为 0容量为 16
@ -16,34 +17,30 @@ func newArrayStack() *arrayStack {
}
}
// size 栈的长度
/* 栈的长度 */
func (s *arrayStack) size() int {
return len(s.data)
}
// isEmpty 栈是否为空
/* 栈是否为空 */
func (s *arrayStack) isEmpty() bool {
return s.size() == 0
}
// push 入栈
/* 入栈 */
func (s *arrayStack) push(v int) {
// 切片会自动扩容
s.data = append(s.data, v)
}
// pop 出栈
/* 出栈 */
func (s *arrayStack) pop() any {
// 弹出栈前,先判断是否为空
if s.isEmpty() {
return nil
}
val := s.peek()
s.data = s.data[:len(s.data)-1]
return val
}
// peek 获取栈顶元素
/* 获取栈顶元素 */
func (s *arrayStack) peek() any {
if s.isEmpty() {
return nil
@ -52,7 +49,7 @@ func (s *arrayStack) peek() any {
return val
}
// 获取 Slice 用于打印
/* 获取 Slice 用于打印 */
func (s *arrayStack) toSlice() []int {
return s.data
}

View File

@ -8,29 +8,30 @@ import (
"container/list"
)
// linkedListDeque 基于链表实现的双端队列, 使用内置包 list 来实现栈
/* 基于链表实现的双端队列 */
type linkedListDeque struct {
// 使用内置包 list 来实现栈
data *list.List
}
// newLinkedListDeque 初始化双端队列
/* 初始化双端队列 */
func newLinkedListDeque() *linkedListDeque {
return &linkedListDeque{
data: list.New(),
}
}
// pushFirst 队首元素入队
/* 队首元素入队 */
func (s *linkedListDeque) pushFirst(value any) {
s.data.PushFront(value)
}
// pushLast 队尾元素入队
/* 队尾元素入队 */
func (s *linkedListDeque) pushLast(value any) {
s.data.PushBack(value)
}
// pollFirst 队首元素出队
/* 队首元素出队 */
func (s *linkedListDeque) pollFirst() any {
if s.isEmpty() {
return nil
@ -40,7 +41,7 @@ func (s *linkedListDeque) pollFirst() any {
return e.Value
}
// pollLast 队尾元素出队
/* 队尾元素出队 */
func (s *linkedListDeque) pollLast() any {
if s.isEmpty() {
return nil
@ -50,7 +51,7 @@ func (s *linkedListDeque) pollLast() any {
return e.Value
}
// peekFirst 访问队首元素
/* 访问队首元素 */
func (s *linkedListDeque) peekFirst() any {
if s.isEmpty() {
return nil
@ -59,7 +60,7 @@ func (s *linkedListDeque) peekFirst() any {
return e.Value
}
// peekLast 访问队尾元素
/* 访问队尾元素 */
func (s *linkedListDeque) peekLast() any {
if s.isEmpty() {
return nil
@ -68,17 +69,17 @@ func (s *linkedListDeque) peekLast() any {
return e.Value
}
// size 获取队列的长度
/* 获取队列的长度 */
func (s *linkedListDeque) size() int {
return s.data.Len()
}
// isEmpty 判断队列是否为空
/* 判断队列是否为空 */
func (s *linkedListDeque) isEmpty() bool {
return s.data.Len() == 0
}
// 获取 List 用于打印
/* 获取 List 用于打印 */
func (s *linkedListDeque) toList() *list.List {
return s.data
}

View File

@ -14,19 +14,19 @@ type linkedListQueue struct {
data *list.List
}
// newLinkedListQueue 初始化链表
/* 初始化队列 */
func newLinkedListQueue() *linkedListQueue {
return &linkedListQueue{
data: list.New(),
}
}
// push 入队
/* 入队 */
func (s *linkedListQueue) push(value any) {
s.data.PushBack(value)
}
// poll 出队
/* 出队 */
func (s *linkedListQueue) poll() any {
if s.isEmpty() {
return nil
@ -36,7 +36,7 @@ func (s *linkedListQueue) poll() any {
return e.Value
}
// peek 访问队首元素
/* 访问队首元素 */
func (s *linkedListQueue) peek() any {
if s.isEmpty() {
return nil
@ -45,17 +45,17 @@ func (s *linkedListQueue) peek() any {
return e.Value
}
// size 获取队列的长度
/* 获取队列的长度 */
func (s *linkedListQueue) size() int {
return s.data.Len()
}
// isEmpty 判断队列是否为空
/* 判断队列是否为空 */
func (s *linkedListQueue) isEmpty() bool {
return s.data.Len() == 0
}
// 获取 List 用于打印
/* 获取 List 用于打印 */
func (s *linkedListQueue) toList() *list.List {
return s.data
}

View File

@ -14,19 +14,19 @@ type linkedListStack struct {
data *list.List
}
// newLinkedListStack 初始化链表
/* 初始化栈 */
func newLinkedListStack() *linkedListStack {
return &linkedListStack{
data: list.New(),
}
}
// push 入栈
/* 入栈 */
func (s *linkedListStack) push(value int) {
s.data.PushBack(value)
}
// pop 出栈
/* 出栈 */
func (s *linkedListStack) pop() any {
if s.isEmpty() {
return nil
@ -36,7 +36,7 @@ func (s *linkedListStack) pop() any {
return e.Value
}
// peek 访问栈顶元素
/* 访问栈顶元素 */
func (s *linkedListStack) peek() any {
if s.isEmpty() {
return nil
@ -45,17 +45,17 @@ func (s *linkedListStack) peek() any {
return e.Value
}
// size 获取栈的长度
/* 获取栈的长度 */
func (s *linkedListStack) size() int {
return s.data.Len()
}
// isEmpty 判断栈是否为空
/* 判断栈是否为空 */
func (s *linkedListStack) isEmpty() bool {
return s.data.Len() == 0
}
// 获取 List 用于打印
/* 获取 List 用于打印 */
func (s *linkedListStack) toList() *list.List {
return s.data
}

View File

@ -7,17 +7,17 @@ package chapter_tree
import . "github.com/krahets/hello-algo/pkg"
/* AVL 树 */
type avlTree struct {
type aVLTree struct {
// 根结点
root *TreeNode
}
func newAVLTree() *avlTree {
return &avlTree{root: nil}
func newAVLTree() *aVLTree {
return &aVLTree{root: nil}
}
/* 获取结点高度 */
func height(node *TreeNode) int {
func (t *aVLTree) height(node *TreeNode) int {
// 空结点高度为 -1 ,叶结点高度为 0
if node != nil {
return node.Height
@ -26,9 +26,9 @@ func height(node *TreeNode) int {
}
/* 更新结点高度 */
func updateHeight(node *TreeNode) {
lh := height(node.Left)
rh := height(node.Right)
func (t *aVLTree) updateHeight(node *TreeNode) {
lh := t.height(node.Left)
rh := t.height(node.Right)
// 结点高度等于最高子树高度 + 1
if lh > rh {
node.Height = lh + 1
@ -38,68 +38,68 @@ func updateHeight(node *TreeNode) {
}
/* 获取平衡因子 */
func balanceFactor(node *TreeNode) int {
func (t *aVLTree) balanceFactor(node *TreeNode) int {
// 空结点平衡因子为 0
if node == nil {
return 0
}
// 结点平衡因子 = 左子树高度 - 右子树高度
return height(node.Left) - height(node.Right)
return t.height(node.Left) - t.height(node.Right)
}
/* 右旋操作 */
func rightRotate(node *TreeNode) *TreeNode {
func (t *aVLTree) rightRotate(node *TreeNode) *TreeNode {
child := node.Left
grandChild := child.Right
// 以 child 为原点,将 node 向右旋转
child.Right = node
node.Left = grandChild
// 更新结点高度
updateHeight(node)
updateHeight(child)
t.updateHeight(node)
t.updateHeight(child)
// 返回旋转后子树的根结点
return child
}
/* 左旋操作 */
func leftRotate(node *TreeNode) *TreeNode {
func (t *aVLTree) leftRotate(node *TreeNode) *TreeNode {
child := node.Right
grandChild := child.Left
// 以 child 为原点,将 node 向左旋转
child.Left = node
node.Right = grandChild
// 更新结点高度
updateHeight(node)
updateHeight(child)
t.updateHeight(node)
t.updateHeight(child)
// 返回旋转后子树的根结点
return child
}
/* 执行旋转操作,使该子树重新恢复平衡 */
func rotate(node *TreeNode) *TreeNode {
func (t *aVLTree) rotate(node *TreeNode) *TreeNode {
// 获取结点 node 的平衡因子
// Go 推荐短变量,这里 bf 指代 balanceFactor
bf := balanceFactor(node)
// Go 推荐短变量,这里 bf 指代 t.balanceFactor
bf := t.balanceFactor(node)
// 左偏树
if bf > 1 {
if balanceFactor(node.Left) >= 0 {
if t.balanceFactor(node.Left) >= 0 {
// 右旋
return rightRotate(node)
return t.rightRotate(node)
} else {
// 先左旋后右旋
node.Left = leftRotate(node.Left)
return rightRotate(node)
node.Left = t.leftRotate(node.Left)
return t.rightRotate(node)
}
}
// 右偏树
if bf < -1 {
if balanceFactor(node.Right) <= 0 {
if t.balanceFactor(node.Right) <= 0 {
// 左旋
return leftRotate(node)
return t.leftRotate(node)
} else {
// 先右旋后左旋
node.Right = rightRotate(node.Right)
return leftRotate(node)
node.Right = t.rightRotate(node.Right)
return t.leftRotate(node)
}
}
// 平衡树,无需旋转,直接返回
@ -107,49 +107,49 @@ func rotate(node *TreeNode) *TreeNode {
}
/* 插入结点 */
func (t *avlTree) insert(val int) *TreeNode {
t.root = insertHelper(t.root, val)
func (t *aVLTree) insert(val int) *TreeNode {
t.root = t.insertHelper(t.root, val)
return t.root
}
/* 递归插入结点(辅助函数) */
func insertHelper(node *TreeNode, val int) *TreeNode {
func (t *aVLTree) insertHelper(node *TreeNode, val int) *TreeNode {
if node == nil {
return NewTreeNode(val)
}
/* 1. 查找插入位置,并插入结点 */
if val < node.Val {
node.Left = insertHelper(node.Left, val)
node.Left = t.insertHelper(node.Left, val)
} else if val > node.Val {
node.Right = insertHelper(node.Right, val)
node.Right = t.insertHelper(node.Right, val)
} else {
// 重复结点不插入,直接返回
return node
}
// 更新结点高度
updateHeight(node)
t.updateHeight(node)
/* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node)
node = t.rotate(node)
// 返回子树的根结点
return node
}
/* 删除结点 */
func (t *avlTree) remove(val int) *TreeNode {
root := removeHelper(t.root, val)
func (t *aVLTree) remove(val int) *TreeNode {
root := t.removeHelper(t.root, val)
return root
}
/* 递归删除结点(辅助函数) */
func removeHelper(node *TreeNode, val int) *TreeNode {
func (t *aVLTree) removeHelper(node *TreeNode, val int) *TreeNode {
if node == nil {
return nil
}
/* 1. 查找结点,并删除之 */
if val < node.Val {
node.Left = removeHelper(node.Left, val)
node.Left = t.removeHelper(node.Left, val)
} else if val > node.Val {
node.Right = removeHelper(node.Right, val)
node.Right = t.removeHelper(node.Right, val)
} else {
if node.Left == nil || node.Right == nil {
child := node.Left
@ -165,21 +165,21 @@ func removeHelper(node *TreeNode, val int) *TreeNode {
}
} else {
// 子结点数量 = 2 ,则将中序遍历的下个结点删除,并用该结点替换当前结点
temp := getInOrderNext(node.Right)
node.Right = removeHelper(node.Right, temp.Val)
temp := t.getInOrderNext(node.Right)
node.Right = t.removeHelper(node.Right, temp.Val)
node.Val = temp.Val
}
}
// 更新结点高度
updateHeight(node)
t.updateHeight(node)
/* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node)
node = t.rotate(node)
// 返回子树的根结点
return node
}
/* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */
func getInOrderNext(node *TreeNode) *TreeNode {
func (t *aVLTree) getInOrderNext(node *TreeNode) *TreeNode {
if node == nil {
return node
}
@ -191,7 +191,7 @@ func getInOrderNext(node *TreeNode) *TreeNode {
}
/* 查找结点 */
func (t *avlTree) search(val int) *TreeNode {
func (t *aVLTree) search(val int) *TreeNode {
cur := t.root
// 循环查找,越过叶结点后跳出
for cur != nil {

View File

@ -41,13 +41,13 @@ func TestAVLTree(t *testing.T) {
fmt.Printf("\n查找到的结点对象为 %#v ,结点值 = %d \n", node, node.Val)
}
func testInsert(tree *avlTree, val int) {
func testInsert(tree *aVLTree, val int) {
tree.insert(val)
fmt.Printf("\n插入结点 %d 后AVL 树为 \n", val)
PrintTree(tree.root)
}
func testRemove(tree *avlTree, val int) {
func testRemove(tree *aVLTree, val int) {
tree.remove(val)
fmt.Printf("\n删除结点 %d 后AVL 树为 \n", val)
PrintTree(tree.root)

View File

@ -15,12 +15,26 @@ type binarySearchTree struct {
}
func newBinarySearchTree(nums []int) *binarySearchTree {
// sorting array
// 排序数组
sort.Ints(nums)
root := buildBinarySearchTree(nums, 0, len(nums)-1)
return &binarySearchTree{
root: root,
// 构建二叉搜索树
bst := &binarySearchTree{}
bst.root = bst.buildTree(nums, 0, len(nums)-1)
return bst
}
/* 构建二叉搜索树 */
func (bst *binarySearchTree) buildTree(nums []int, left, right int) *TreeNode {
if left > right {
return nil
}
// 将数组中间结点作为根结点
middle := left + (right-left)>>1
root := NewTreeNode(nums[middle])
// 递归构建左子树和右子树
root.Left = bst.buildTree(nums, left, middle-1)
root.Right = bst.buildTree(nums, middle+1, right)
return root
}
/* 获取根结点 */
@ -146,21 +160,7 @@ func (bst *binarySearchTree) remove(num int) *TreeNode {
return cur
}
// buildBinarySearchTree Build a binary search tree from array.
func buildBinarySearchTree(nums []int, left, right int) *TreeNode {
if left > right {
return nil
}
// 将数组中间结点作为根结点
middle := left + (right-left)>>1
root := NewTreeNode(nums[middle])
// 递归构建左子树和右子树
root.Left = buildBinarySearchTree(nums, left, middle-1)
root.Right = buildBinarySearchTree(nums, middle+1, right)
return root
}
// print binary search tree
/* 打印二叉搜索树 */
func (bst *binarySearchTree) print() {
PrintTree(bst.root)
}

View File

@ -11,7 +11,7 @@ import (
)
/* 层序遍历 */
func levelOrder(root *TreeNode) []int {
func hierOrder(root *TreeNode) []int {
// 初始化队列,加入根结点
queue := list.New()
queue.PushBack(root)

View File

@ -11,7 +11,7 @@ import (
. "github.com/krahets/hello-algo/pkg"
)
func TestLevelOrder(t *testing.T) {
func TestHierOrder(t *testing.T) {
/* 初始化二叉树 */
// 这里借助了一个从数组直接生成二叉树的函数
root := ArrToTree([]any{1, 2, 3, 4, 5, 6, 7})
@ -19,6 +19,6 @@ func TestLevelOrder(t *testing.T) {
PrintTree(root)
// 层序遍历
nums := levelOrder(root)
nums := hierOrder(root)
fmt.Println("\n层序遍历的结点打印序列 =", nums)
}