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))
相关推荐
希望有朝一日能如愿以偿几秒前
力扣每日一题:使数组和能被p整除
数据结构·算法·leetcode
Christo34 分钟前
AAAI-2013《Spectral Rotation versus K-Means in Spectral Clustering》
人工智能·算法·机器学习·数据挖掘·kmeans
葵花楹5 分钟前
【补题】【atcoderabc434】【codeforces1067】
算法
老黄编程6 分钟前
详细解释计算协方差矩阵 C(3D Harris),并给出计算样例及步骤
线性代数·矩阵·3d harris 协方差矩阵
roman_日积跬步-终至千里12 分钟前
【模式识别与机器学习】AdaBoost算法:集成学习的基本原理与AdaBoost算法的应用
算法·机器学习·集成学习
mit6.82415 分钟前
中位数贪心|前缀和_距离和ret=l+r_1
算法
一匹电信狗16 分钟前
【LeetCode】栈和队列进阶题目
c++·算法·leetcode·职场和发展·stl·栈和队列
机器学习之心18 分钟前
198种组合算法+优化TCN时间卷积神经网络+SHAP分析+新数据预测+多输出!深度学习可解释分析,强烈安利,粉丝必备!
深度学习·算法·shap分析·tcn时间卷积神经网络
代码游侠19 分钟前
数据结构——线性表
linux·c语言·数据结构·学习·算法
吃着火锅x唱着歌21 分钟前
LeetCode 3371.识别数组中的最大异常值
数据结构·算法·leetcode