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))
相关推荐
shehuiyuelaiyuehao1 天前
算法14,滑动窗口,找到字符串中所有字母异位词
算法
凯瑟琳.奥古斯特1 天前
图论核心考点精讲
开发语言·数据结构·算法·排序算法·哈希算法
WolfGang0073211 天前
代码随想录算法训练营 Day49 | 图论 part07
算法·图论
啦啦啦_99991 天前
案例之 逻辑回归_癌症预测
算法·机器学习·逻辑回归
StockTV1 天前
韩国股票实时数据 KOSPI(主板)和 KOSDAQ(创业板)的实时行情、K 线及指数数据
java·开发语言·算法·php
byte轻骑兵1 天前
【LE Audio】BASS精讲[5]: 状态特征解析,广播接收状态实时可视全流程
人工智能·算法·音视频·语音识别·le audio·低功耗音频
m0_629494731 天前
LeetCode 热题 100-----13.最大子数组和
数据结构·算法·leetcode
0xR3lativ1ty1 天前
大模型算法原理高频题解析
算法
故事还在继续吗1 天前
STL 容器算法手册
开发语言·c++·算法
田梓燊1 天前
力扣:94.二叉树的中序遍历
数据结构·算法·leetcode