38. Search a 2D Matrix II

題目

https://www.lintcode.com/problem/search-a-2d-matrix-ii/description?_from=ladder&&fromId=2

實現

  1. 從左下角開始往右上角移動
  2. 如果 matrix[x][y] > target 那麼往右移動
  3. 如果 matrix[x][y] < target 那麼往上移動
  4. 如果相待,那麼計數 + 1,並往右上移動一個單位

代碼

class Solution:
    """
    @param matrix: A list of lists of integers
    @param target: An integer you want to search in matrix
    @return: An integer indicate the total occurrence of target in the given matrix
    """
    def searchMatrix(self, matrix, target):
        if matrix is None or len(matrix) == 0 or len(matrix[0]) == 0:
            return 0

        rows, cols = len(matrix), len(matrix[0])

        x, y = rows - 1, 0
        count = 0
        while x >= 0 and y < cols:
            if matrix[x][y] < target:
                # Shift right
                y += 1
            elif matrix[x][y] > target:
                # Shift top
                x -= 1
            else:
                x -= 1
                y += 1
                count += 1

        return count
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章