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,這樣寫出來(lái)的代碼又長(zhǎng)效率也不高。
參考了九章算法中的方法,思路是:從矩陣的左下角開始,若此值等于target則結(jié)束返回True;若此值大于target,那么正一行值都必定大于target,因此指針向上移動(dòng)1,即拋棄當(dāng)前行;若此值小于target,那么這一列都必定小于target,因此指針向右移1,即拋棄當(dāng)前列。
起始位置也可以選在右上角,方法基本一樣。

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.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容