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

解题思路:
这个 matrix 的排序比较特别,是从左到右递增,从上到下递增 可以从第一行的最右边开始查找,如果目标值大于矩阵值可以排除左边的,如果目标值小于矩阵值可以排除下面的

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """

        r = len(matrix)
        if r == 0:
            return False
        c = len(matrix[0])
        if c == 0:
            return False
        x , y = 0 , c - 1
        while x < r and y >= 0:
            # print(r,c)
            print(x,y)
            print(matrix[x][y])
            if matrix[x][y] == target:
                return True
            elif matrix[x][y] < target:
                x += 1
            else:
                y -= 1
        return False

请多多指教。

文章标题:240. Search a 2D Matrix II

本文作者:顺强

发布时间:2019-04-03, 23:59:00

原始链接:http://shunqiang.ml/leetcode-240-search-a-2D-m-2/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏