From e0721dde050cac7142b9742cdefb09c69711db84 Mon Sep 17 00:00:00 2001 From: machangxin Date: Sat, 17 Dec 2022 14:59:21 +0800 Subject: [PATCH 1/2] function PrintSlice supports Generics --- codes/go/pkg/print_utils.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codes/go/pkg/print_utils.go b/codes/go/pkg/print_utils.go index 3d9b83a2..a42d48b2 100644 --- a/codes/go/pkg/print_utils.go +++ b/codes/go/pkg/print_utils.go @@ -11,7 +11,8 @@ import ( "strings" ) -func PrintSlice(nums []int) { +// PrintSlice Print a slice +func PrintSlice[T any](nums []T) { fmt.Printf("%v", nums) fmt.Println() } From 2305b09db4935fb123fffc5a77f6c1663566fac4 Mon Sep 17 00:00:00 2001 From: machangxin Date: Sat, 17 Dec 2022 15:14:38 +0800 Subject: [PATCH 2/2] Supplement linear_search documentation --- codes/go/chapter_searching/linear_search.go | 7 +++--- docs/chapter_searching/linear_search.md | 27 +++++++++++++++++++-- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/codes/go/chapter_searching/linear_search.go b/codes/go/chapter_searching/linear_search.go index ee06debd..25603751 100644 --- a/codes/go/chapter_searching/linear_search.go +++ b/codes/go/chapter_searching/linear_search.go @@ -8,12 +8,12 @@ import ( . "github.com/krahets/hello-algo/pkg" ) -// linerSearchArray 线性查找(数组) +/* 线性查找(数组) */ func linerSearchArray(nums []int, target int) int { // 遍历数组 for i := 0; i < len(nums); i++ { + // 找到目标元素,返回其索引 if nums[i] == target { - // 找到目标元素,返回其索引 return i } } @@ -21,10 +21,11 @@ func linerSearchArray(nums []int, target int) int { return -1 } -// linerSearchLinkedList 线性查找(链表) +/* 线性查找(链表) */ func linerSearchLinkedList(node *ListNode, target int) *ListNode { // 遍历链表 for node != nil { + // 找到目标元素,返回其索引 if node.Val == target { return node } diff --git a/docs/chapter_searching/linear_search.md b/docs/chapter_searching/linear_search.md index e635c7d0..8822d375 100644 --- a/docs/chapter_searching/linear_search.md +++ b/docs/chapter_searching/linear_search.md @@ -59,7 +59,18 @@ comments: true === "Go" ```go title="linear_search.go" - + /* 线性查找(数组) */ + func linerSearchArray(nums []int, target int) int { + // 遍历数组 + for i := 0; i < len(nums); i++ { + // 找到目标元素,返回其索引 + if nums[i] == target { + return i + } + } + // 未找到目标元素,返回 -1 + return -1 + } ``` === "JavaScript" @@ -138,7 +149,19 @@ comments: true === "Go" ```go title="linear_search.go" - + /* 线性查找(链表)*/ + func linerSearchLinkedList(node *ListNode, target int) *ListNode { + // 遍历链表 + for node != nil { + // 找到目标结点,返回之 + if node.Val == target { + return node + } + node = node.Next + } + // 未找到目标元素,返回 nil + return nil + } ``` === "JavaScript"