Leetcode-74題:Search a 2D Matrix

題目

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 from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,

Consider the following matrix:

[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.

思路

從矩陣的最右端元素開始考慮,如果它比所求要大,那么在當(dāng)前行查找即可。否則,進(jìn)入下一行。

代碼

class Solution(object):

    def binarySearch(self, nums, l, r, target):
        if l > r:
            return False
        m = l + (r-l)/2
        if nums[m] == target:
            return True
        elif nums[m] > target:
            return self.binarySearch(nums, l, m-1, target)
        else:
            return self.binarySearch(nums, m+1, r, target)

    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if matrix==None or len(matrix)==0:
            return False
        m = len(matrix)
        n = len(matrix[0])
        i = 0
        while i < m:
            if matrix[i][n-1] == target:
                return True
            elif matrix[i][n-1] > target:
                return self.binarySearch(matrix[i], 0, n-1, target)
            else:
                i += 1
        return False
最后編輯于
?著作權(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),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 【養(yǎng)心養(yǎng)意】 20171027 學(xué)習(xí)力踐行 Day17 ^o^晨起英語喚醒《小鱷魚愛洗澡》 ^o^督促我讀詩兩首 ...
    愛己及人閱讀 157評(píng)論 0 0
  • 器械劃船 60lbs 10*4組 65lbs 8*4組 繩索夾胸 20lbs 12*2組 ...
    范范范小北閱讀 250評(píng)論 0 0
  • 不知從何時(shí)起,有兩個(gè)本來挺不錯(cuò)的詞,硬生生被用壞了。我看養(yǎng)生,危險(xiǎn),再不拯救,恐怕也要淪落風(fēng)塵,甚至臭大街了。 一...
    阿努伽耶閱讀 962評(píng)論 0 0
  • 20210623 銷售的最高境界就是讓對(duì)方感覺到一個(gè)想法是他腦中自己的想法,盡管這個(gè)想法是你灌輸給他的。而我不行,...
    道行者閱讀 821評(píng)論 0 50

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