码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Search a 2D Matrix

时间:2016-01-22 18:17:57      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

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) 来获得相关源码。

LeetCode Search a 2D Matrix

标签:

原文地址:http://blog.csdn.net/u013291394/article/details/50557303

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!