Update linear_search and hashing_search.

This commit is contained in:
Yudong Jin
2023-02-04 23:49:37 +08:00
parent 62114ce79a
commit f14e3e4c57
22 changed files with 95 additions and 92 deletions

View File

@ -7,7 +7,7 @@ package chapter_searching
import . "github.com/krahets/hello-algo/pkg"
/* 哈希查找(数组) */
func hashingSearch(m map[int]int, target int) int {
func hashingSearchArray(m map[int]int, target int) int {
// 哈希表的 key: 目标元素value: 索引
// 若哈希表中无此 key ,返回 -1
if index, ok := m[target]; ok {
@ -18,7 +18,7 @@ func hashingSearch(m map[int]int, target int) int {
}
/* 哈希查找(链表) */
func hashingSearch1(m map[int]*ListNode, target int) *ListNode {
func hashingSearchLinkedList(m map[int]*ListNode, target int) *ListNode {
// 哈希表的 key: 目标结点值value: 结点对象
// 若哈希表中无此 key ,返回 nil
if node, ok := m[target]; ok {

View File

@ -20,7 +20,7 @@ func TestHashingSearch(t *testing.T) {
for i := 0; i < len(nums); i++ {
m[nums[i]] = i
}
index := hashingSearch(m, target)
index := hashingSearchArray(m, target)
fmt.Println("目标元素 3 的索引 = ", index)
/* 哈希查找(链表) */
@ -31,6 +31,6 @@ func TestHashingSearch(t *testing.T) {
m1[head.Val] = head
head = head.Next
}
node := hashingSearch1(m1, target)
node := hashingSearchLinkedList(m1, target)
fmt.Println("目标结点值 3 的对应结点对象为 ", node)
}

View File

@ -9,7 +9,7 @@ import (
)
/* 线性查找(数组) */
func linerSearchArray(nums []int, target int) int {
func linearSearchArray(nums []int, target int) int {
// 遍历数组
for i := 0; i < len(nums); i++ {
// 找到目标元素,返回其索引
@ -22,7 +22,7 @@ func linerSearchArray(nums []int, target int) int {
}
/* 线性查找(链表) */
func linerSearchLinkedList(node *ListNode, target int) *ListNode {
func linearSearchLinkedList(node *ListNode, target int) *ListNode {
// 遍历链表
for node != nil {
// 找到目标元素,返回其索引

View File

@ -16,11 +16,11 @@ func TestLinearSearch(t *testing.T) {
nums := []int{1, 5, 3, 2, 4, 7, 5, 9, 10, 8}
// 在数组中执行线性查找
index := linerSearchArray(nums, target)
index := linearSearchArray(nums, target)
fmt.Println("目标元素 3 的索引 =", index)
// 在链表中执行线性查找
head := ArrayToLinkedList(nums)
node := linerSearchLinkedList(head, target)
node := linearSearchLinkedList(head, target)
fmt.Println("目标结点值 3 的对应结点对象为", node)
}