Skip to content

Latest commit

 

History

History
101 lines (76 loc) · 1.95 KB

20200719-240.search-a-2d-matrix-ii.md

File metadata and controls

101 lines (76 loc) · 1.95 KB

#240.search-a-2d-matrix-ii

题目链接:https://leetcode-cn.com/problems/search-a-2d-matrix-ii/

参考链接:https://leetcode-cn.com/problems/search-a-2d-matrix-ii/solution/sou-suo-er-wei-ju-zhen-ii-by-leetcode-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

解题

思路[1]暴力法

  • 双层遍历,查找到就返回true,反之,返回false

代码

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var searchMatrix = function(matrix, target) {
  for(let i = 0; i < matrix.length; i++){
    let matrix_n = matrix[i]
    for(let j = 0; j < matrix_n.length; j++){
      if(matrix_n[j] === target){
        return true
      }
    }
  }
  return false
};

思路[2]寻找

  • 从左下角开始遍历,比较当前数和target,然后移动指针。
  • 如果当前数比target小则说明这一行中可能存在这个数,则向右寻找
  • 如果当前数比target大则说明这一行中都比这个数大,则向下寻找下一行
  • 一直到超出边界

代码

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var searchMatrix = function(matrix, target) {
  let row = matrix.length - 1, col = 0;

  while(row >= 0 && col < matrix[0].length){
    let item = matrix[row][col];
    if(item === target){
      return true
    }
    if(item > target){
      row--;
      continue;
    }
    if(item < target){
      col++;
      continue;
    }
  }
  return false
};

思考

  • 二分法和搜索空间法暂时搁置