LintCode 28题:Search a 2D Matrix

这篇文章讲解的是LintCode第28题:在二维数组中查找target—Search a 2D Matrix

题目描述链接

此二维数组的每一行中右侧的数大于左侧的,并且每行第一个元素大于上一行最右侧的元素。

Example
Example 1:
	Input:  [[5]],2
	Output: false
	
	Explanation: 
	false if not included.
	
Example 2:
	Input:  [
    [1, 3, 5, 7],
    [10, 11, 16, 20],
    [23, 30, 34, 50]
],3
	Output: true
	
	Explanation: 
	return true if included.

可以使用二分查找法来做,只需确定mid 的横纵坐标:

def searchMatrix(self, matrix, target):
        # write your code here
        
        if not matrix:
            return False
            
        row, column = len(matrix), len(matrix[0])
        start, end = 0, row * column - 1
        while start + 1 < end:
            mid = start + (end - start) // 2
            num = matrix[mid // column][mid % column]
            if num < target:
                start = mid
            elif num > target:
                end = mid
            else:
                return True
        return matrix[start // column][start % column] == target or matrix[end // column][end % column] == target

注意最后一行不能直接retrun False,因为这样会漏掉target在两侧上的情况。

当然也可以直接查找:

    def searchMatrix(self, matrix, target):
        """
        直接查找
        :param matrix:
        :param target:
        :return:
        """
        if not matrix:
            return False

        row, column = 0, len(matrix[0]) - 1
        while row < len(matrix) and column >= 0:
            if matrix[row][column] == target:
                return True
            elif matrix[row][column] < target:
                row += 1
            else:
                column -= 1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值