美文网首页
[Array]240. Search a 2D Matrix I

[Array]240. Search a 2D Matrix I

作者: 野生小熊猫 | 来源:发表于2019-01-31 00:44 被阅读0次
    • 分类:Array
    • 时间复杂度: O(m+n)

    240. Search a 2D Matrix II

    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 in ascending from left to right.
    • Integers in each column are sorted in ascending from top to bottom.

    Example:

    Consider the following matrix:

    [
      [1,   4,  7, 11, 15],
      [2,   5,  8, 12, 19],
      [3,   6,  9, 16, 22],
      [10, 13, 14, 17, 24],
      [18, 21, 23, 26, 30]
    ]
    

    Given target = 5, return true.

    Given target = 20, return false.

    代码:

    非常直接的方法:

    class Solution:
        def searchMatrix(self, matrix, target):
            """
            :type matrix: List[List[int]]
            :type target: int
            :rtype: bool
            """
            #边界条件
            if (matrix==None or len(matrix)==0 or len(matrix[0])==0):
                return False
            
            m=len(matrix)
            n=len(matrix[0])
            i=0
            j=n-1
            
            while(i<m and j>=0):
                if matrix[i][j]==target:
                    return True
                elif matrix[i][j]>target:
                    j-=1
                else:
                    i+=1
                    
            return False
    

    讨论:

    1.这道题我看到的解法好像和分治无关,不知道为什么这个题要分到分治这个类别里?好像和DP的关系更大?


    240做法

    相关文章

      网友评论

          本文标题:[Array]240. Search a 2D Matrix I

          本文链接:https://www.haomeiwen.com/subject/ahihsqtx.html