LeetCode Search a 2D Matrix

LeetCode解题之Search a 2D Matrix


原题

在一个每行从左到右依次递增,且下一行第一个数字比上一行最后一个数字大的矩阵中,判断目标数字是否存在。

注意点:

例子:

输入:

matrix = 
[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3

输出: True

解题思路

把矩阵从左到右、从上到下连起来就是一个递增的数组,可以用二分搜索来查找。现在只要找出数组下标到矩阵的映射关系就可以了:i -> [i // n][i % n],其中i是数组中的下标,n是矩阵的宽。

AC源码

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        m = len(matrix)
        n = len(matrix[0])
        l, h = 0, m * n - 1
        while l <= h:
            mid = l + (h - l) // 2
            if matrix[mid // n][mid % n] == target:
                return True
            elif matrix[mid // n][mid % n] < target:
                l = mid + 1
            else:
                h = mid - 1
        return False


if __name__ == "__main__":
    assert Solution().searchMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 5) == True
    assert Solution().searchMatrix([[1, 2], [3, 4]], 4) == True
    assert Solution().searchMatrix([[1]], 2) == False

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值