Skip to content

Latest commit

 

History

History
28 lines (26 loc) · 892 Bytes

74.md

File metadata and controls

28 lines (26 loc) · 892 Bytes

https://leetcode-cn.com/problems/search-a-2d-matrix/

思路

二维矩阵在内存中都是线性存储的,二维矩阵 m * n 某个点坐标 [x, y] 在一维矩阵中的对应坐标 为 pos = x * n + n, 相应的,如果知道一维矩阵坐标 pos ,我们可以得到其在二维矩阵中的坐标 x = pos // n, y = pos % n

代码

var searchMatrix = function (matrix, target) {
  if (!matrix.length) {
    return false;
  }
  const m = matrix.length;
  const n = matrix[0].length;
  let left = 0,
    right = m * n - 1;
  while (left <= right) {
    const mid = (left + right) >> 1;
    if (matrix[Math.floor(mid / n)][mid % n] === target) {
      return true;
    } else if (matrix[Math.floor(mid / n)][mid % n] < target) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }
  return false;
};