feat(go): support basic pkg
This commit is contained in:
35
codes/go/chapter_searching/linear_search.go
Normal file
35
codes/go/chapter_searching/linear_search.go
Normal file
@@ -0,0 +1,35 @@
|
||||
// File: linear_search.go
|
||||
// Created Time: 2022-11-25
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_searching
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
// 未找到目标元素,返回 -1
|
||||
return -1
|
||||
}
|
||||
|
||||
// linerSearchLinkedList 线性查找(链表)
|
||||
func linerSearchLinkedList(node *ListNode, target int) *ListNode {
|
||||
// 遍历链表
|
||||
for node != nil {
|
||||
if node.Val == target {
|
||||
return node
|
||||
}
|
||||
node = node.Next
|
||||
}
|
||||
// 未找到目标元素,返回 nil
|
||||
return nil
|
||||
}
|
||||
24
codes/go/chapter_searching/linear_search_test.go
Normal file
24
codes/go/chapter_searching/linear_search_test.go
Normal file
@@ -0,0 +1,24 @@
|
||||
// File: linear_search_test.go
|
||||
// Created Time: 2022-11-25
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_searching
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLinearSearch(t *testing.T) {
|
||||
target := 3
|
||||
nums := []int{1, 5, 3, 2, 4, 7, 5, 9, 10, 8}
|
||||
|
||||
// 在数组中执行线性查找
|
||||
index := linerSearchArray(nums, target)
|
||||
t.Log("目标元素 3 的索引 = ", index)
|
||||
|
||||
// 在链表中执行线性查找
|
||||
head := ArrayToLinkedListLinkedList(nums)
|
||||
node := linerSearchLinkedList(head, target)
|
||||
t.Log("目标结点值 3 的对应结点对象为 ", node)
|
||||
}
|
||||
Reference in New Issue
Block a user