LeetCode-in-All

74. Search a 2D Matrix

Medium

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

Example 1:

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

Output: true

Example 2:

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

Output: false

Constraints:

Solution

defmodule Solution do
  @spec search_matrix(matrix :: [[integer]], target :: integer) :: boolean
  def search_matrix(matrix, target) do
    matrix = matrix |> Enum.map(&List.to_tuple/1) |> List.to_tuple()
    binary_search(matrix, 0, tuple_size(matrix) * tuple_size(elem(matrix, 0)) - 1, target)
  end

  defp binary_search(_matrix, left, right, _target) when left > right, do: false

  defp binary_search(matrix, left, right, target) do
    mid = div(right + left, 2)
    cols = matrix |> elem(0) |> tuple_size()
    mid_elem = matrix |> elem(div(mid, cols)) |> elem(rem(mid, cols))

    cond do
      mid_elem > target -> binary_search(matrix, left, right - 1, target)
      mid_elem < target -> binary_search(matrix, mid + 1, right, target)
      mid_elem == target -> true
    end
  end
end