面试题-搜索二维矩阵中是否存在目标值

题目来源:

https://leetcode-cn.com/problems/search-a-2d-matrix/

https://leetcode-cn.com/problems/search-a-2d-matrix-ii/

最简单的是暴力遍历,好一点的可以用二分查找。

但是这两题其实可以用同一个思路解决:

从矩阵的左下角或者右上角开始判断,以左下角开始为例:

  • 左下角等于target值,返回True
  • 左下角小于target值,对于同一列,上一行肯定是小于下一行的,那么只能往右走,行索引-1,继续判断。
  • 左下角大于target值,对于同一行,右侧列肯定会大于左侧列,那么只能往上走,列索引+1,继续判断。
  • 重复这个过程,直到列索引超出c-1,或是行索引低于0。

另外注意特殊情况,matrix为[]或是[[]]的判断。

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix or not matrix[0]:
            return False
        
        r = len(matrix)
        c = len(matrix[0])

        nr = r-1
        nc = 0
        while nr >= 0 and nr < r and nc >= 0 and nc < c:
            if matrix[nr][nc] == target:
                return True
            elif matrix[nr][nc] < target:
                nc += 1
            elif matrix[nr][nc] > target:
                nr -= 1
        return False

参考:

https://leetcode-cn.com/problems/search-a-2d-matrix-ii/solution/sou-suo-er-wei-ju-zhen-ii-by-leetcode-2/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值