📜  门| GATE CS Mock 2018 |设置 2 |第 45 题(1)

📅  最后修改于: 2023-12-03 15:12:38.121000             🧑  作者: Mango

GATE CS Mock 2018 - Set 2 - Question 45

This question is about implementing a function that takes a 2D array of integers and a target value as input and returns a boolean value indicating whether the target value is present in the 2D array or not. The function should have the following signature:

def search_matrix(matrix: List[List[int]], target: int) -> bool:
    pass
Approach

The given 2D matrix is sorted row-wise, which means each row is sorted in ascending order. Therefore, we can use binary search on each row to find the target value. If the target value is less than the first element of a row or greater than the last element of a row, we move to the next row.

Algorithm
  1. Initialize m to the number of rows in the matrix and n to the number of columns in the matrix.
  2. Initialize left to 0 and right to m * n - 1.
  3. While left <= right, repeat steps 4 through 7.
  4. Compute the middle index mid as (left + right) // 2.
  5. Compute the row index row as mid // n.
  6. Compute the column index col as mid % n.
  7. If the target value is present at matrix[row][col], return True. If the target value is less than matrix[row][col], set right to mid - 1. Otherwise, set left to mid + 1.
  8. If the target value is not found, return False.
Code
from typing import List

def search_matrix(matrix: List[List[int]], target: int) -> bool:
    m, n = len(matrix), len(matrix[0])
    left, right = 0, m * n - 1
    while left <= right:
        mid = (left + right) // 2
        row, col = mid // n, mid % n
        if matrix[row][col] == target:
            return True
        elif matrix[row][col] < target:
            left = mid + 1
        else:
            right = mid - 1
    return False

The time complexity of this algorithm is O(log(mn)), where m is the number of rows and n is the number of columns in the 2D matrix. The space complexity is O(1), since we are not using any additional data structures.