LeetCode 74. 搜索二维矩阵

题目描述

74. 搜索二维矩阵

image-20230305215009775

image-20230305215013608

思路分析

这个问题的关键是矩阵具有升序的性质:每行从左到右升序排列,每列从上到下升序排列。

image-20250510192334893

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func searchMatrix(matrix [][]int, target int) bool {
	if len(matrix) == 0 || len(matrix[0]) == 0 {
		return false
	}

	// 从右上角开始
	row, col := 0, len(matrix[0])-1

	for row < len(matrix) && col >= 0 {
		if matrix[row][col] == target {
			return true
		} else if matrix[row][col] > target {
			col--
		} else {
			row++
		}
	}

	return false
}
  • 时间复杂度O(m + n),其中 m 是矩阵的行数,n 是矩阵的列数。
  • 空间复杂度O(1),只使用常数级别的额外空间。

image-20250507205216811

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func searchMatrix(matrix [][]int, target int) bool {
	if len(matrix) == 0 || len(matrix[0]) == 0 {
		return false
	}

	m, n := len(matrix), len(matrix[0])
	left, right := 0, m*n-1

	for left <= right {
		mid := left + (right-left)/2
		row := mid / n // 计算对应的行
		col := mid % n // 计算对应的列

		if matrix[row][col] == target {
			return true
		} else if matrix[row][col] < target {
			left = mid + 1
		} else {
			right = mid - 1
		}
	}

	return false
}
  • 时间复杂度O(log(m * n)),其中 m 是矩阵的行数,n 是矩阵的列数。
  • 空间复杂度O(1),只使用常数级别的额外空间。

➡️ 点击查看 Java 题解

1
write your code here

image-20250507205253519

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