LeetCode 240. 搜索二维矩阵 II

题目描述

240. 搜索二维矩阵 II

image-20230304223309803

image-20230304223319332

思路分析

我们从矩阵的右上角开始搜索,通过调整行或列来缩小搜索范围。

image-20250507201911750

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func searchMatrix(matrix [][]int, target int) bool {
	if len(matrix) == 0 || len(matrix[0]) == 0 {
		return false
	}
	m, n := len(matrix)-1, len(matrix[0])-1
	i, j := 0, n
	for i <= m && j >= 0 {
		if matrix[i][j] > target {
			j--
		} else if matrix[i][j] < target {
			i++
		} else {
			return true
		}
	}
	return false
}
  • 时间复杂度:O (m + n),其中 m 是行数,n 是列数。
  • 空间复杂度:O (1),只使用了常数级别的额外空间。

➡️ 点击查看 Java 题解

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/47047341
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!