面试150 搜索二维矩阵

思路1

直接遍历搜寻,逐个判断即可

python 复制代码
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m=len(matrix)
        n=len(matrix[0])
        for i in range(m):
            for j in range(n):
                if matrix[i][j]==target:
                    return True
        return False

思路2

Z字形搜索从矩阵的右上角(第一行最后一列)开始。若当前元素等于 target,则返回 True。如果当前元素小于 target,说明目标可能在更大的元素中,将行索引加一(向下移动);反之,若当前元素大于 target,则列索引减一(向左移动)。重复上述过程,直到找到目标或越界结束搜索。

python 复制代码
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m, n = len(matrix), len(matrix[0])
        
        # 从右上角开始搜索
        i, j = 0, n - 1
        
        while i < m and j >= 0:
            if matrix[i][j] == target:
                return True
            elif matrix[i][j] > target:
                j -= 1  # 向左移动
            else:
                i += 1  # 向下移动
        
        return False
相关推荐
JianZhen✓18 小时前
电商 SKU 选择器:后端只给扁平列表,前端怎么反推规格矩阵并做到 O(1) 命中
前端·矩阵·状态模式
2601_967979122 天前
简单学Python——NumPy库6——数值计算1——累加和累乘
数值计算·numpy·数组·累加·累乘
tellmewhoisi4 天前
深度学习0:数学知识:(雅可比矩阵)
人工智能·深度学习·矩阵
拂拉氏7 天前
【知识讲解-题目讲解】 统计满足K约束的子字符串数量2 (滑动窗口+前缀和+二分查找+分析)
算法·前缀和·二分查找·滑动窗口
lisw0510 天前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
DFT计算杂谈10 天前
可DIY布里渊区图像绘制编辑器
人工智能·机器学习·语言模型·矩阵·编辑器
Pniubi10 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵
Pniubi11 天前
力扣73 矩阵置零
算法·leetcode·矩阵
kingx312 天前
Bugku 逆向 MatrixHunter:黑盒 oracle + GF(2) 消元出唯一解
网络安全·矩阵·逆向·ctf