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))
相关推荐
18538162800余--22 分钟前
矩阵系统源码搭建热门音乐功能板块开发,支持OEM
线性代数·矩阵
缘友一世36 分钟前
从线性回归到逻辑回归
算法·逻辑回归·线性回归
前端_学习之路1 小时前
javaScript--数据结构和算法
javascript·数据结构·算法
weixin_428498492 小时前
使用HYPRE库并行装配IJ稀疏矩阵指南: 矩阵预分配和重复利用
算法·矩阵
雾削木4 小时前
mAh 与 Wh:电量单位的深度解析
开发语言·c++·单片机·嵌入式硬件·算法·电脑
__lost4 小时前
小球在摆线上下落的物理过程MATLAB代码
开发语言·算法·matlab
mit6.8245 小时前
[Lc_week] 447 | 155 | Q1 | hash | pair {}调用
算法·leetcode·哈希算法·散列表
巷北夜未央5 小时前
空间矩阵的思考
线性代数·矩阵
jerry6096 小时前
优先队列、堆笔记(算法第四版)
java·笔记·算法
勤劳的牛马7 小时前
📚 小白学算法 | 每日一题 | 算法实战:加1!
算法