LeetCode-in-All

74. Search a 2D Matrix

Medium

Write an efficient algorithm that searches for a value in an m x n 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

# @param {Integer[][]} matrix
# @param {Integer} target
# @return {Boolean}
def search_matrix(matrix, target)
  end_col = matrix[0].length
  target_row = 0
  result = false

  matrix.each_with_index do |row, i|
    if row[end_col - 1] >= target
      target_row = i
      break
    end
  end

  matrix[target_row].each_with_index do |element, i|
    if element == target
      result = true
      break
    end
  end

  return result
end