Merge branch 'master' into master

This commit is contained in:
Yudong Jin
2023-01-02 18:53:33 +08:00
committed by GitHub
21 changed files with 216 additions and 71 deletions

View File

@@ -1,6 +1,6 @@
// File: array.go
// Created Time: 2022-12-29
// Author: cathay (cathaycchen@gmail.com)
// Author: GuoWei (gongguowei01@gmail.com), cathay (cathaycchen@gmail.com)
package chapter_array_and_linkedlist
@@ -9,11 +9,18 @@ import (
"math/rand"
)
/**
我们将 Go 中的 Slice 切片看作 Array 数组,降低理解成本,
有利于我们将关注点放在数据结构与算法上。
*/
/* 随机返回一个数组元素 */
func randomAccess(nums []int) int {
func randomAccess(nums []int) (randomNum int) {
// 在区间 [0, nums.length) 中随机抽取一个数字
randomIndex := rand.Intn(len(nums))
randomNum := nums[randomIndex]
return randomNum
// 获取并返回随机元素
randomNum = nums[randomIndex]
return
}
/* 扩展数组长度 */
@@ -21,8 +28,8 @@ func extend(nums []int, enlarge int) []int {
// 初始化一个扩展长度后的数组
res := make([]int, len(nums)+enlarge)
// 将原数组中的所有元素复制到新数组
for i, num := range nums {
res[i] = num
for i := 0; i < len(nums); i++ {
res[i] = nums[i]
}
// 返回扩展后的新数组
return res
@@ -53,22 +60,20 @@ func traverse(nums []int) {
for i := 0; i < len(nums); i++ {
count++
}
fmt.Println(count)
count = 0
// 直接遍历数组
for range nums {
count++
for index, val := range nums {
fmt.Printf("index:%v value:%v\n", index, val)
}
fmt.Println(count)
}
/* 在数组中查找指定元素,返回第一个索引位置,未查找到则返回 -1 */
func find(nums []int, target int) int {
/* 在数组中查找指定元素 */
func find(nums []int, target int) (index int) {
index = -1
for i := 0; i < len(nums); i++ {
if nums[i] == target {
return i
index = i
break
}
}
return -1
return
}

View File

@@ -1,9 +1,14 @@
// File: array_test.go
// Created Time: 2022-12-29
// Author: cathay (cathaycchen@gmail.com)
// Author: GuoWei (gongguowei01@gmail.com), cathay (cathaycchen@gmail.com)
package chapter_array_and_linkedlist
/**
我们将 Go 中的 Slice 切片看作 Array 数组。因为这样可以
降低理解成本,利于我们将关注点放在数据结构与算法上。
*/
import (
"fmt"
"testing"
@@ -12,10 +17,9 @@ import (
/* Driver Code */
func TestArray(t *testing.T) {
/* 初始化数组 */
var arr = [5]int{}
var arr []int
fmt.Println("数组 arr =", arr)
var nums = []int{1, 3, 2, 5, 4}
nums := []int{1, 3, 2, 5, 4}
fmt.Println("数组 nums =", nums)
/* 随机访问 */
@@ -32,7 +36,7 @@ func TestArray(t *testing.T) {
/* 删除元素 */
remove(nums, 2)
fmt.Println("删除索引 2 处的元素,得到 nums = ", nums)
fmt.Println("删除索引 2 处的元素,得到 nums =", nums)
/* 遍历数组 */
traverse(nums)