menu

[LeetCode] 074. Search a 2D Matrix

Problem (Medium)

074. 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

Approach 1: Binary Search *

Idea

A typical binary search problem.

Solution

class Solution1:
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not len(matrix) or not len(matrix[0]):
            return False
        row_num, col_num = len(matrix), len(matrix[0])
        begin, end = 0, row_num * col_num - 1
        while begin <= end:
            mid = (begin + end) // 2
            mid_val = matrix[mid//col_num][mid%col_num]
            if mid_val == target:
                return True
            if mid_val < target:
                begin = mid + 1
            else:
                end = mid - 1
        return False

Complexity

  • Time: $O(\log (MN))$ where $M,N$ are the width and height of the input matrix.
  • Space: $O(1)$



KF

Comments