package main
import "fmt"
func main() {
matrix := [][]int{
{1, 4, 7, 11, 15},
{2, 5, 8, 12, 19},
{3, 6, 9, 16, 22},
{10, 13, 14, 17, 24},
{18, 21, 23, 26, 30},
}
exist := searchMatrix(matrix, 5)
fmt.Println("exit", exist)
}
func searchMatrix(matrix [][]int, target int) bool {
if matrix == nil || len(matrix) == 0 || len(matrix[0]) == 0 {
return false
}
row := 0
col := len(matrix[0]) - 1
for col >= 0 && row <= len(matrix)-1 {
if matrix[row][col] == target {
return true
} else if matrix[row][col] > target {
col--
} else if matrix[row][col] < target {
row++
}
}
return false
}
转载于:https://www.cnblogs.com/w3liu/p/10850374.html
本文介绍了一种在二维矩阵中搜索特定元素的高效算法。通过利用矩阵的有序特性,该算法能够在O(log n)的时间复杂度内完成搜索,适用于大数据量的场景。文章提供了完整的Go语言实现代码,并通过具体示例展示了算法的工作流程。
153

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



