LeetCode 74 [Search a 2D Matrix]

原題

寫出一個(gè)高效的算法來搜索 m × n矩陣中的值。
這個(gè)矩陣具有以下特性:
每行中的整數(shù)從左到右是排序的。
每行的第一個(gè)數(shù)大于上一行的最后一個(gè)整數(shù)。

[
  [1, 3, 5, 7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

給出 target = 3,返回 true

解題思路

  • 首先可以把這個(gè)二維數(shù)組看成一維數(shù)組,3 * 4 的矩陣可以看成一個(gè)12個(gè)數(shù)的一維數(shù)組,所以對(duì)于50的坐標(biāo)為(2,3),可以看成第array[11]
[1, 3, 5, 7, 10, 11, 16, 20, 23, 30, 34, 50]
  • 一維數(shù)組與二維數(shù)組的轉(zhuǎn)化
2 = 11 / 4, 3 = 11 % 4   # width = 4

完整代碼

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix:
            return False
        
        start = 0
        width = len(matrix[0])
        end = len(matrix) * width - 1
        while start + 1 < end:
            mid = start + (end - start) / 2
            if matrix[mid / width][mid % width] == target:
                return True
            elif matrix[mid / width][mid % width] > target:
                end = mid
            else:
                start = mid
            
        if matrix[start / width][start % width] == target:
            return True
        if matrix[end / width][end % width] == target:
            return True
        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),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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