LeetCode知识点总结 - 240

LeetCode 240. Search a 2D Matrix II

考点难度
MatrixMedium
题目

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.

思路

如果M[r][c]小于target说明应该向下面找(同一行的左边和同一列上边都比target小)所以继续移动直到大于target然后向左移动再判断
直到移动到matrix左下角,如果找到了返回true,没有找到返回false

答案
class Solution:
    def searchMatrix(self, matrix, target):
        m, n = len(matrix), len(matrix) and len(matrix[0])
        r, c = 0, n-1
        while r < m and c >= 0:
            if target > matrix[r][c]:
                r += 1
            elif target < matrix[r][c]:
                c -= 1
            else: return True
        return False
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值