1. 程式人生 > >LeetCode74:Search a 2D Matrix

LeetCode74: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.

Example 1:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false

LeetCode:連結

第一種解法:和 劍指Offer_程式設計題01:二維陣列中的查詢是一樣的。

首先選取陣列中右上角的數字。如果要選左上角的數字,target比它大,是應該向右找還是應該向左找呢?這個是不確定的。所以應該從可以確定方向的數字開始找其。如果該數字等於要查詢的數字,查詢過程結束;如果該數字大於要查詢的陣列,就向它前一列找,如果該數字小於要查詢的陣列,就向他下一行找。

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if len(matrix) == 0:
            return False
        row = len(matrix)
        col = len(matrix[0])
        i, j = 0, col - 1
        while i < row and j >= 0:
            if target == matrix[i][j]:
                return True
            elif target > matrix[i][j]:
                i += 1
            else:
                j -= 1
        return False

第二種方法:兩次二分。一開始先確定行,取每行第一個數進行查詢。之後在這一行進行查詢該元素。

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if len(matrix) == 0 or matrix == [[]]:
            return False
        row = len(matrix)
        col = len(matrix[0])
        # 必須用索引形式記錄row的最大值 如果接下來在確定row的時候沒有符合要求的 得返回row的最大索引 row-1 
        cur_row = row - 1
        for i in range(row):
            # 必須得是小於等於 如果不等於 就完全錯過了這一排
            if target <= matrix[i][col-1]:
                cur_row = i
                break
        low = 0
        high = col - 1
        while low <= high:
            mid = (low + high) // 2
            if matrix[cur_row][mid] == target:
                return True
            elif matrix[cur_row][mid] > target:
                high = mid - 1
            else:
                low = mid + 1
        return False

第三種方法:正是因為有The first integer of each row is greater than the last integer of the previous row.條件的存在,可以直接把矩陣看成一維的,即L=0,R=m*n-1,而每次matrix[mid/n][mid%n]即可。

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix:
            return False
        m, n = len(matrix), len(matrix[0])
        low, high = 0, m*n - 1
        while low <= high:
            mid = (low + high) // 2
            if matrix[mid//n][mid%n] == target:
                return True
            elif matrix[mid//n][mid%n] > target:
                high = mid - 1
            else:
                low = mid + 1
        return False