LeetCode | 搜索二维矩阵

520 字
3 分钟
LeetCode | 搜索二维矩阵

分类:二分查找 / 数组 / 矩阵

题目#

给你一个满足下述两条属性的 m x n 整数矩阵:

  • 每行中的整数从左到右按非严格递增顺序排列。
  • 每行的第一个整数大于前一行的最后一个整数。

给你一个整数 target ,如果 target 在矩阵中,返回 true ;否则,返回 false

讲解#

二分法。

一维二分#

看成一维数组,在 [0, m * n) 这个范围里做二分,找第一个大于等于 target 的位置。

两次二分#

第二种方法是做两次二分。

第一次二分先找 target 可能在哪一行。

找到这一行之后,再对这一行做一次普通二分查找。

复杂度#

  • 一维二分:
    • 时间复杂度:O(log(m * n))
    • 空间复杂度:O(1)
  • 两次二分:
    • 时间复杂度:O(log(m) + log(n))
    • 空间复杂度:O(1)

因为 log(m) + log(n) = log(m * n),所以两种方法的时间复杂度本质上是一样的。

代码#

一维二分#

源码#

from typing import List
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m = len(matrix)
n = len(matrix[0])
left = 0
right = m * n
while left < right:
mid = (left + right) // 2
x = matrix[mid // n][mid % n]
if x < target:
left = mid + 1
else:
right = mid
return left < m * n and matrix[left // n][left % n] == target

两次二分#

源码#

from typing import List
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m = len(matrix)
n = len(matrix[0])
top = 0
bottom = m - 1
while top <= bottom:
row = (top + bottom) // 2
if matrix[row][0] <= target <= matrix[row][n - 1]:
break
if matrix[row][0] > target:
bottom = row - 1
else:
top = row + 1
if top > bottom:
return False
left = 0
right = n - 1
while left <= right:
mid = (left + right) // 2
if matrix[row][mid] == target:
return True
if matrix[row][mid] < target:
left = mid + 1
else:
right = mid - 1
return False

测试#

from src.python._074_Search_A_2D_Matrix import Solution
sol = Solution()
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]
assert sol.searchMatrix(matrix, 3) is True
assert sol.searchMatrix(matrix, 13) is False
assert sol.searchMatrix([[1]], 1) is True
assert sol.searchMatrix([[1]], 2) is False
print("PASS")

参考资料#

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

LeetCode | 搜索二维矩阵
https://leetcode.com/problems/search-a-2d-matrix/
作者
平昊阳
发布于
2026-08-04
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
平昊阳
乘长风,破巨浪, 展鸿图于未央!
--
总访问量
--
访客数
公告
欢迎来到我的个人博客!欢迎关注交流吖!
更多相关公告,见
社交-留言」。
音乐
封面

音乐

暂未播放

0:000:00
暂无歌词
站点统计
文章
66
分类
16
标签
93
总字数
477,284
运行时长
0
最后活动
0 天前

文章目录