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

问题分析

开始我的想法是先用二分法找到可能包含target的行,再在这些行里用二分法查找target,这样写出来的代码又长效率也不高。
参考了九章算法中的方法,思路是:从矩阵的左下角开始,若此值等于target则结束返回True;若此值大于target,那么正一行值都必定大于target,因此指针向上移动1,即抛弃当前行;若此值小于target,那么这一列都必定小于target,因此指针向右移1,即抛弃当前列。
起始位置也可以选在右上角,方法基本一样。

AC代码

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        n = len(matrix)
        m = len(matrix[0])
        p = n-1
        q = 0
        while p >= 0 and q < m:
            if matrix[p][q] == target:
                return True
            if matrix[p][q] > target:
                p -= 1
            else:
                q += 1
        return False

Runtime 112 ms, which beats 75.61% of Python submissions.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容