原题链接:https://leetcode.cn/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/
通过dfs+记忆化来解,应该是O(log(n + m))
func findNumberIn2DArray(matrix [][]int, target int) bool {
n := len(matrix)
if n == 0 {
return false
}
m := len(matrix[0])
if m == 0 {
return false
}
memo := make([][]int, n)
for i := range memo {
memo[i] = make([]int, m)
for j := range memo[i] {
memo[i][j] = -1
}
}
var dfs func(i, j int) bool
dfs = func(i, j int) bool {
if memo[i][j] != -1 {
return memo[i][j] == 1
}
if i + 1 < n {
d := matrix[i + 1][j]
if d == target {
return true
}
if d < target {
if dfs(i + 1, j) {
return true
}
}
}
if j + 1 < m {
r := matrix[i][j + 1]
if r == target {
return true
}
if r < target {
if dfs(i, j + 1) {
return true
}
}
}
memo[i][j] = 0
return false
}
if matrix[0][0] == target {
return true
}
return dfs(0, 0)
}
优化方法,从右上角看,数组就想一个二叉排序树(Binary Sort Tree),那么就好做了,时间复杂度为O(m+n)
func findNumberIn2DArray(matrix [][]int, target int) bool {
n := len(matrix)
if n == 0 {
return false
}
m := len(matrix[0])
if m == 0 {
return false
}
i, j := 0, m - 1
for i < n && j >= 0 {
num := matrix[i][j]
if target == num {
return true
} else if target > num {
i++
} else {
j--
}
}
return false
}