Leetcode-74题:Search a 2D Matrix

题目

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,

Consider the following matrix:

[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.

思路

从矩阵的最右端元素开始考虑,如果它比所求要大,那么在当前行查找即可。否则,进入下一行。

代码

class Solution(object):

    def binarySearch(self, nums, l, r, target):
        if l > r:
            return False
        m = l + (r-l)/2
        if nums[m] == target:
            return True
        elif nums[m] > target:
            return self.binarySearch(nums, l, m-1, target)
        else:
            return self.binarySearch(nums, m+1, r, target)

    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if matrix==None or len(matrix)==0:
            return False
        m = len(matrix)
        n = len(matrix[0])
        i = 0
        while i < m:
            if matrix[i][n-1] == target:
                return True
            elif matrix[i][n-1] > target:
                return self.binarySearch(matrix[i], 0, n-1, target)
            else:
                i += 1
        return False
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 【养心养意】 20171027 学习力践行 Day17 ^o^晨起英语唤醒《小鳄鱼爱洗澡》 ^o^督促我读诗两首 ...
    爱己及人阅读 1,243评论 0 0
  • 器械划船 60lbs 10*4组 65lbs 8*4组 绳索夹胸 20lbs 12*2组 ...
    范范范小北阅读 1,643评论 0 0
  • 不知从何时起,有两个本来挺不错的词,硬生生被用坏了。我看养生,危险,再不拯救,恐怕也要沦落风尘,甚至臭大街了。 一...
    阿努伽耶阅读 4,386评论 0 0
  • 20210623 销售的最高境界就是让对方感觉到一个想法是他脑中自己的想法,尽管这个想法是你灌输给他的。而我不行,...
    道行者阅读 4,114评论 0 50

友情链接更多精彩内容