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))
相关推荐
Maỿbe10 分钟前
力扣hot图论部分
算法·leetcode·图论
LYFlied18 分钟前
【每日算法】LeetCode 78. 子集
数据结构·算法·leetcode·面试·职场和发展
月明长歌22 分钟前
【码道初阶】【Leetcode606】二叉树转字符串:前序遍历 + 括号精简规则,一次递归搞定
java·数据结构·算法·leetcode·二叉树
子枫秋月23 分钟前
C++字符串操作与迭代器解析
数据结构·算法
鹿角片ljp23 分钟前
力扣234.回文链表-反转后半链表
算法·leetcode·链表
(●—●)橘子……24 分钟前
记力扣1471.数组中的k个最强值 练习理解
数据结构·python·学习·算法·leetcode
oioihoii27 分钟前
C++共享内存小白入门指南
java·c++·算法
Bruce_kaizy29 分钟前
c++图论————图的基本与遍历
c++·算法·图论
l1t32 分钟前
利用小米mimo为精确覆盖矩形问题C程序添加打乱函数求出更大的解
c语言·开发语言·javascript·人工智能·算法
亭上秋和景清35 分钟前
strlen;strcpy ;strcat
算法