[JavaScript 刷题] 二分搜索 - 搜索二维矩阵, leetcode 74

[JavaScript 刷题] 二分搜索 - 搜索二维矩阵, leetcode 74

github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。

题目地址:74. Search a 2D Matrix

题目

如下:

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

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

解题思路

题目给的提示应该已经挺明显的了,首先所有的数字都是由左到右进行了排序;其次每行第一个数字永远比上一列的数字小。

这样就可以把一个矩阵始做一个数组进行二分搜索,如:

1 3 5 7
10 11 16 20
23 30 34 60

其实就可以视作一个数组:

1 3 5 7 10 11 16 20 23 30 34 60

将数组扁平化是一个方法,不过这样就会需要额外的空间和时间去进行操作。另一种方法是通过使用 除 和 模 的方式去获得 index。这样就需要使用 length / col 去获得当前行,以及 length % col 获得当前列。

如,以上面的表格为例,lohi 分别对应 011,这个时候的 mid 就是 5. 使用上面的公式就可以获得行为 5 / 4 = 1 5 / 4 = 1 5/4=1,列为 5 % 4 = 1 5 \% 4 = 1 5%4=1

使用 JavaScript 解题

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var searchMatrix = function (matrix, target) {
    
    
  const maxR = matrix.length;
  if (maxR === 0) return false;
  const maxC = matrix[0].length;
  let left = 0,
    right = maxR * maxC - 1;

  let mid, midEl;
  while (left <= right) {
    
    
    mid = Math.floor((left + right) / 2);

    midEl = matrix[Math.floor(mid / maxC)][mid % maxC];

    if (target === midEl) return true;

    if (target < midEl) right = mid - 1;
    else left = mid + 1;
  }

  return false;
};

猜你喜欢

转载自blog.csdn.net/weixin_42938619/article/details/125157940