240、搜索二维矩阵II

1.暴力破解

这种就是一个个比较矩阵中的值与目标值,相等返回True;否则返回False。

代码

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        for row in matrix:
            for v in row:
                if v == target:
                    return True
        return False

2.二分查找

有序数组对于二分查找非常有利,对矩阵中的每个数组进行二分查找,如果找到,返回True;否则返回False。

代码

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        for row in matrix:
		    index = bisect.bisect_left(row, target)
		    if index < len(row) and row[index] == target:
			    return True
	    return False

3.Z字法

因为矩阵行列都是递增的,可以利用这一内在联系,去除掉不合格的选项。从右上角出发,如果大于target,说明列都是大于target的,下面的列就不需要判断了,往左移动一列;如果小于target,说明当前行不需要判断了,向下移动一行。

这个倒是没有想起来。

代码

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        x, y = 0, len(matrix[0])-1  
	    while x < len(matrix) and y > -1:
		    if matrix[x][y] > target:
			    y -= 1
		    elif matrix[x][y] < target:
			    x += 1
		    else:
			    return True
	    return False


链接:https://leetcode-cn.com/problems/search-a-2d-matrix-ii/solution/240-sou-suo-er-wei-ju-zhen-ii-by-senlind-qj66/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值