对二分查找的模板不熟悉的可以先去看:LeetCode704 二分查找。
// javascript
var searchMatrix = function(matrix, target) {
if (matrix === null || matrix.length === 0 || matrix[0].length === 0) return false;
const m = matrix.length, n = matrix[0].length;
let left = 0, right = m * n - 1;
while (left <= right) {
const mid = left + ((right - left) >> 1);
const midVal = matrix[Math.floor(mid / n)][mid % n]; // 找到在数组中的位置
if (midVal > target) right = mid - 1;
else if (midVal < target) left = mid + 1;
else return true;
}
return false;
};
// javascript
var searchMatrix = function(matrix, target) {
const rowIndex = binarySearchFirstColumn(matrix, target);
if (rowIndex < 0) return false; // target < matrix[0][0]
return binarySearchRow(matrix[rowIndex], target);
};
// 在第一列,找到最后一个小于等于 target 的元素所在行
const binarySearchFirstColumn = (matrix, target) => {
let left = -1, right = matrix.length - 1;
while (left < right) {
const mid = left + ((right - left + 1) >> 1);
if (matrix[mid][0] <= target) {
left = mid;
} else {
right = mid - 1;
}
}
return left;
}
const binarySearchRow = (row, target) => {
let left = 0, right = row.length - 1;
while (left <= right) {
const mid = left + ((right - left) >> 1);
if (row[mid] > target) right = mid - 1;
else if (row[mid] < target) left = mid + 1;
else return true;
}
return false;
}
两种方法殊途同归,都利用了二分查找,在二维矩阵上寻找目标值。值得注意的是,若二维数组中的一维数组的元素个数不一,方法一将会失效,而方法二则能正确处理。
// javascript
var searchMatrix = function(matrix, target) {
const m = matrix.length, n = matrix[0].length;
let i = m - 1, j = 0;
while (i >= 0 && j < n) {
if (matrix[i][j] > target) i--;
else if (matrix[i][j] < target) j++;
else return true;
}
return false;
};