[leetcode] 240. Search a 2D Matrix II

題目大意

https://leetcode.com/problems/search-a-2d-matrix-ii/web

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:ide

Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
Example:測試

Consider the following matrix:spa

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

Given target = 20, return false.blog

編寫一個高效的算法,從一個m × n矩陣中尋找一個值。矩陣具備以下性質:ci

每一行的整數從左向右遞增
每一列的整數從上往下遞增leetcode

測試樣例見題目描述。get

 

解題思路

解法一:從矩陣的右上角(屏幕座標系)開始,執行兩重循環;外循環遞增枚舉每行,內循環遞減枚舉列

class Solution(object):
    def searchMatrix(self, matrix, target):  # 48ms
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not len(matrix) or not len(matrix[0]):
            return False
        m, n = len(matrix), len(matrix[0])
        r, c = 0, n - 1
        while r < m and c >= 0:
            if matrix[r][c] == target:
                return True
            elif matrix[r][c] > target:
                c -= 1
            else:
                r += 1
        return False

算法複雜度:O(m + n)

 

相似思路的實現:

class Solution(object):        
    def searchMatrix(self, matrix, target):  # 48ms
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not len(matrix) or not len(matrix[0]):
            return False
        y = len(matrix[0]) - 1
        for x in range(len(matrix)):
            while y and matrix[x][y] > target:
                y -= 1
            if matrix[x][y] == target:
                return True
        return False

 

解法二:循環枚舉行,二分查找列

class Solution(object):       
    def searchMatrix(self, matrix, target):  # 二分查找 148ms
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not len(matrix) or not len(matrix[0]):
            return False
        y = len(matrix[0]) - 1
        
        def binary_search(nums, low, high):
            while low <= high:
                mid = (low + high) / 2
                if nums[mid] > target:
                    high = mid - 1
                else:
                    low = mid + 1
            return high

算法複雜度:O(m * logn)

 

參考:

http://bookshadow.com/weblog/2015/07/23/leetcode-search-2d-matrix-ii/

https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/183609/An-intelligible-Python-solution-beats-99.64-48ms

相關文章
相關標籤/搜索