240. Search a 2D Matrix II

来源:互联网 发布:西部世界好看吗 知乎 编辑:程序博客网 时间:2024/06/05 06:57

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.

For 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.

java

class Solution {    public boolean searchMatrix(int[][] matrix, int target) {        if (matrix == null || matrix.length == 0) {            return false;        }        if (matrix[0] == null || matrix[0].length == 0) {            return false;        }        int row = 0;        int column = matrix[0].length - 1;        while (row < matrix.length && column >= 0) {            if (matrix[row][column] == target) {                return true;            } else if (matrix[row][column] > target) {                column--;            } else {                row++;            }        }        return false;    }}

python

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


原创粉丝点击