LeetCode 74 Search a 2D Matrix(Python详解及实现)

来源:互联网 发布:广联达翻样软件多少钱 编辑:程序博客网 时间:2024/05/22 04:40

【题目】

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

 

Integers in each row are sorted from leftto right.

The first integer of each row is greaterthan the last integer of the previous row.

 

在一个m*n二维数组中,判断某个元素是否在该数组中。

 

每一行从左到右递增,每一行的第一个元素比上一行最后一个元素大。

 

【思路】

思路一:对于每行从左到右递增,从上到下也是递增的。(TLE)

         从矩阵的左上角出发,第零行,如果当前值【0,0】比target小,且【0,n-1】比target         大的话,列索引加1,继续比较;如果且【0,n-1】比target小的话,行索引加1,继续         比较。

 

思路二:先在列二分查找定位列,然后再二分查找,定位行注意边界条件

 

注意:在列查找的时候,发现low-1小于0时,直接返回False。

【Python实现】

class Solution(object):

   def searchMatrix(self, matrix, target):

       """

       :type matrix: List[List[int]]

       :type target: int

       :rtype: bool

       """

       m = len(matrix)

       if m == 0 :

           return False

       n = len(matrix[0])

       if n == 0:

           return False

       low = 0

       high = m - 1

 

       while low <= high:

           mid = (low + high) // 2

           if matrix[mid][0] == target:

                return True

           elif matrix[mid][0] > target:

                high = mid - 1

           else:

                low = mid + 1

       row = low - 1

       if row < 0:

           row = 0

       low = 0

       high = n - 1

       while low <= high:

           mid = (low + high) // 2

           if matrix[row][mid] == target:

                #print(matrix[row][mid])

                return True

           elif matrix[row][mid] > target:

                high = mid - 1

           else:

                low = mid + 1

       return False

 

                   

if __name__ == '__main__':

    S= Solution()

   matrix =[[1,   3,  5, 7],[10, 11, 16, 20],[23, 30, 34, 50]]

   target = 20

   S.searchMatrix( matrix,target)          

原创粉丝点击