文章目录
搜索二维矩阵
示例 1:
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true
示例 2:
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
输出:false
我的思路
var searchMatrix = function (matrix, target) {
if (matrix.length === 0 || matrix[0].length === 0) {
return false;
}
const rows = matrix.length;
const cols = matrix[0].length;
for (let i = 0; i < rows; i++) {
if (target < matrix[i][0]) {
return false;
}
if (target > matrix[i][cols - 1]) {
continue;
}
for (let j = 0; j < cols; j++) {
if (matrix[i][j] === target) {
return true;
}
}
}
return false;
};
网上思路
var searchMatrix = function(matrix, target) {
const m = matrix.length, n = matrix[0].length;
let low = 0, high = m * n - 1;
while (low <= high) {
const mid = Math.floor((high - low) / 2) + low;
const x = matrix[Math.floor(mid / n)][mid % n];
if (x < target) {
low = mid + 1;
} else if (x > target) {
high = mid - 1;
} else {
return true;
}
}
return false;
};
总结
很实用,正好我自身有项目在使用二维矩阵,明天我来试试