声明:只求用最简单的方法通过,不求优化,不喜勿喷
- 当成二分查找来做就行了
- 用mid/m和mid%m来处理行列
- 记得Floor来处理一下,js默认不是整数
/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
var searchMatrix = function (matrix, target) {
let n = matrix.length;
let m = matrix[0].length;
let l = 0;
let r = m*n-1;
while(l<=r){
let mid = Math.floor((l+r)/2)
if(matrix[Math.floor(mid/m)][Math.floor(mid%m) ] < target){
l = mid+1;
}else if(matrix[Math.floor(mid/m)][Math.floor(mid% m)] > target){
r = mid-1;
}else{
return true;
}
}
return false;
};