leetcode-mid-sorting and searching

mycode   time limited

def searchMatrix(matrix, target): 
        def deal(data):
            if not data:
                return False
            row = len(data)
            col = len(data[0])
            #print('row,col',row,col)
            for r in range(row):
                for c in range(col):
                    #print(r,c)
                    if data[r][c] == target:
                        return True
                    elif data[r][c] > target:
                        deal(data[r+1:][:c])
        if deal(matrix) :return True
        else:
            return False
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]
]
searchMatrix(matrix, 5)

参考:

1、while循环中问题的关键是,如何不断缩小搜索的范围? -- 从右上角or左下角开始是最好的,因为两个方向的变化是一个变大一个变小

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix or not matrix[0]:
            return False
        rows = len(matrix)
        cols = len(matrix[0])
        row, col = 0, cols - 1
        while True:
            if row < rows and col >= 0:
                if matrix[row][col] == target:
                    return True
                elif matrix[row][col] < target:
                    row += 1
                else:
                    col -= 1
            else:
                return False

2、巧用pyhton

#暴力方法
class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        return any(target in row for row in matrix)
原文地址:https://www.cnblogs.com/rosyYY/p/10978259.html