顺序查找
- 思路
- 遍历数组
- 找到跟目标值相等元素,就返回它的下标
- 没有找到,返回-1
Typescript 版算法实现
1 ) 方案 1
function seqSearch(nums: number[], target: number) {
for(let i = 0; i < nums.length; ++ i) {
if(nums[i] === target) return i;
}
return -1;
}
const list: number[] = [15, 4, 23, 52, 1];
const res1: number = seqSearch(list, 23);
const res2: number = seqSearch(list, 123);
console.log(res1); // 2
console.log(res2); // -1
Python3 版算法实现
1 ) 方案1
def seq_search(nums, target):
for i in range(len(nums)):
if nums[i] == target:
return i
return -1
def test_seq_search():
test_cases = [
([15, 4, 23, 52, 1], 23, 2),
([15, 4, 23, 52, 1], 123, -1),
([1, 2, 3, 4, 5], 3, 2),
([1, 2, 3, 4, 5], 6, -1),
([10, 20, 30, 40, 50], 10, 0),
([10, 20, 30, 40, 50], 50, 4),
([], 1, -1),
([1], 1, 0),
([1], 2, -1),
]
for i, (nums, target, expected) in enumerate(test_cases):
result = seq_search(nums, target)
if result == expected:
print(f"Test Case {i + 1}: PASS (For list {nums} and target {target}, expected {expected}, got {result})")
else:
print(f"Test Case {i + 1}: FAIL (For list {nums} and target {target}, expected {expected}, got {result})")
if __name__ == "__main__":
test_seq_search()
Golang 版算法实现
1 ) 方案1
package main
import (
"fmt"
)
// 顺序查找函数
func seqSearch(nums []int, target int) int {
for i := 0; i < len(nums); i++ {
if nums[i] == target {
return i
}
}
return -1
}
func testSeqSearch() {
testCases := []struct {
list []int
target int
expected int
}{
{[]int{15, 4, 23, 52, 1}, 23, 2},
{[]int{15, 4, 23, 52, 1}, 123, -1},
{[]int{1, 2, 3, 4, 5}, 3, 2},
{[]int{1, 2, 3, 4, 5}, 6, -1},
{[]int{10, 20, 30, 40, 50}, 10, 0},
{[]int{10, 20, 30, 40, 50}, 50, 4},
{[]int{}, 1, -1},
{[]int{1}, 1, 0},
{[]int{1}, 2, -1},
}
for _, tc := range testCases {
result := seqSearch(tc.list, tc.target)
if result == tc.expected {
fmt.Printf("PASS: For list %v and target %d, expected %d, got %d\n", tc.list, tc.target, tc.expected, result)
} else {
fmt.Printf("FAIL: For list %v and target %d, expected %d, got %d\n", tc.list, tc.target, tc.expected, result)
}
}
}
func main() {
testSeqSearch()
}
总结
- 非常低效,算是入门搜索
- 时间复杂度:O(n)
- 对于数组结构或链表结构而言,没什么太多可说的
3686



被折叠的 条评论
为什么被折叠?



