leetcod(003) - 搜索二维矩阵 II

2019/03/04

搜索二维矩阵 II

一、题目描述

1、English版本

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 in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

Example:

Consider the following matrix:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.

2、 中文版

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:

  • 每行的元素从左到右升序排列。
  • 每列的元素从上到下升序排列。

示例:

现有矩阵 matrix 如下:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

给定 target = 5,返回 true

给定 target = 20,返回 false

二、ruby方案

ruby一句include就可以了

# @param {Integer[][]} matrix
# @param {Integer} target
# @return {Boolean}
def search_matrix(matrix, target)
  if matrix.empty?
    return false
  end

  matrix.each do |array|
    if array.include?(target)
      return true
    end
  end

  return false

end

三、python方案

同上

四、java方案

null

五、经典解法,算法思想

剑指offer题目,如果是静态语言并没有include?方法,只能借助题目特点。

##
# 矩阵上下、左右有序, 可以从右上角或者左下角开始遍历;
# 以为有序,与第一个元素相比较,就可以一次去掉一行或者一列不符合的数据
# (以左下角为例)
# @param {Integer[][]} matrix
# @param {Integer} target
# @return {Boolean}
def search_matrix(matrix, target)
  if matrix.empty?
    return false
  end

  row = matrix.size - 1
  cols = matrix[0].size
  col = 0
  while row >= 0 && col < cols do
    array = matrix[row]
    if array[col] == target
      return true
    # 说明该行都大于target,向上递减
    elsif array[col] > target
      row -= 1
      next
    # 说明该列都小于target,向前递加
    else
      col += 1
    end
  end

  return false
end


Show Disqus Comments

Post Directory