Golang 通过线性搜索在数组中找到特定元素的第一个出现
在这篇 Golang 文章中,我们将使用递归和迭代方法,通过线性搜索找到数组中特定元素的第一个出现。
线性搜索是一种简单的搜索算法,它逐个检查列表或数组中的每个元素,从开头开始,直到找到目标值或搜索整个列表。它也被称为顺序搜索。
语法
func firstOcc(arr []int, target int) int {…}
firstOcc() 函数用于使用线性搜索迭代的方式在数组中找到特定元素的第一个出现。它使用整数数组和目标元素作为参数。
func firstOcc(arr []int, target int, index int) int {…}
firstOcc()函数用于使用递归的线性搜索方法在数组中找到特定元素的第一个出现位置。它接受一个整数数组、目标元素和数组的当前索引作为参数。
步骤
- 步骤 1 - 首先,我们需要导入fmt包。
-
步骤 2 - 现在,创建一个firstOcc()函数,它使用线性搜索方法在数组中找到特定元素的第一个出现位置。
-
步骤 3 - 它接受一个数组和一个目标元素作为输入,并返回目标元素在数组中第一个出现位置的索引。
-
步骤 4 - 如果目标元素在数组中未找到,则函数返回-1。
-
步骤 5 - 它使用简单的线性搜索算法从开头遍历数组,并将每个元素与目标元素进行比较。如果找到了目标元素,它将返回那个元素的索引。
-
步骤 6 - 开始main()函数。在main()函数内部,创建一个包含一些元素的数组。
-
步骤 7 - 定义目标元素。
-
步骤 8 - 现在,调用firstOcc()函数,并将数组和目标元素作为参数传递给函数。
-
步骤 9 - 通过使用fmt.Printf()函数,在屏幕上打印出带有目标元素第一次出现位置的索引的结果消息。
示例1
在这个示例中,我们将定义一个使用迭代方法的firstOcc()函数,用于通过线性搜索找到特定元素在数组中的第一个出现位置。
package main
import "fmt"
func firstOcc(arr []int, target int) int {
for i, v := range arr {
if v == target {
return i
}
}
return -1
}
func main() {
arr := []int{4, 8, 3, 2, 7, 4, 5, 9, 10}
target := 9
index := firstOcc(arr, target)
if index == -1 {
fmt.Printf("First Occurrence of element %d not found in array\n", target)
} else {
fmt.Printf("First Occurrence of element %d found at index %d\n", target, index)
}
}
输出
First Occurrence of element 9 found at index 7
示例2
在这个示例中,我们将使用递归的方法来定义一个firstOcc()函数,该函数用于使用线性搜索在数组中找到特定元素的第一个出现。
package main
import "fmt"
func firstOcc(arr []int, target int, index int) int {
if index >= len(arr) {
return -1
}
if arr[index] == target {
return index
}
return firstOcc(arr, target, index+1)
}
func main() {
arr := []int{49, 23, 33, 14, 56, 46, 17, 28, 69, 10}
target := 56
index := firstOcc(arr, target, 0)
if index == -1 {
fmt.Printf("First Occurrence of element %d not found in array\n", target)
} else {
fmt.Printf("First Occurrence of element %d found at index %d\n", target, index)
}
}
输出
First Occurrence of element 56 found at index 4
结论
我们成功编译和执行了一个Go语言程序,使用线性搜索的递归和迭代方法,在数组中找到特定元素的第一个出现位置,并附带两个示例。在第一个示例中,我们使用了迭代方法,在第二个示例中,我们使用了递归方法。