美文网首页
240. Search a 2D Matrix II

240. Search a 2D Matrix II

作者: codingXue | 来源:发表于2016-07-06 11:14 被阅读18次

问题描述

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.

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/eldkjttx.html