leetcode-240. 搜索二维矩阵 II

题目描述

编写一个高效的算法来搜索 m xn 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:

  • 每行的元素从左到右升序排列。
  • 每列的元素从上到下升序排列。

示例 1:

复制代码
输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
输出:true

示例 2:

复制代码
输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
输出:false

思路

1)从第一行,最后一列开始遍历

2)如果等于target,就返回true

3)如果大于target,就col-=1

4)如果小于target,就row+=1

python 复制代码
class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        rows = len(matrix)
        cols = len(matrix[0])
        row = 0
        col = cols-1
        while row<rows and col>=0:
            if matrix[row][col]==target:
                return True
            elif matrix[row][col] > target:
                col -= 1
            else:
                row+=1
        return False

if __name__ == '__main__':
    s = Solution()
    matrix = [[1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24],
              [18, 21, 23, 26, 30]]
    target = 5
    print(s.searchMatrix(matrix, target))
相关推荐
舔甜歌姬的EGUMI LEGACY1 小时前
【算法day28】解数独——编写一个程序,通过填充空格来解决数独问题
算法
welkin1 小时前
KMP 个人理解
前端·算法
半桔1 小时前
红黑树剖析
c语言·开发语言·数据结构·c++·后端·算法
eason_fan1 小时前
前端面试手撕代码(字节)
前端·算法·面试
今天_也很困1 小时前
牛客2025年愚人节比赛
c++·算法
Joe_Wang52 小时前
[图论]拓扑排序
数据结构·c++·算法·leetcode·图论·拓扑排序
2401_858286112 小时前
CD21.【C++ Dev】类和对象(12) 流插入运算符的重载
开发语言·c++·算法·类和对象·运算符重载
梭七y2 小时前
【力扣hot100题】(033)合并K个升序链表
算法·leetcode·链表
月亮被咬碎成星星2 小时前
LeetCode[383]赎金信
算法·leetcode
无难事者若执3 小时前
新手村:逻辑回归-理解03:逻辑回归中的最大似然函数
算法·机器学习·逻辑回归