链接:https://leetcode-cn.com/problems/search-a-2d-matrix
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。
二分法
var searchMatrix = function(matrix, target) {
const array = [].concat(...matrix)
let left = 0; right = array.length - 1;
while(left <= right) {
let mid = (left + right) >> 1;
if (array[mid] === target) return true
if (array[mid] < target) left = mid + 1;
else right = mid - 1
}
return false
};
var searchMatrix = function(matrix, target) {
if (!matrix.length || !matrix[0].length) return false
let m = matrix.length, n = matrix[0].length;
let left = 0, right = m * n - 1;
while (left <= right) {
let mid = (left + right) >> 1, midEle = matrix[parseInt(mid / n)][parseInt(mid % n)];
if (midEle === target) return true;
if (midEle < target) left = mid + 1;
else right = mid - 1
}
return false
}
var searchMatrix = function(matrix, target) {
if (!matrix.length || !matrix[0].length) return false
let row = 0, col = matrix[0].length - 1;
while (col >= 0 && row <= matrix.length - 1) {
if (matrix[row][col] === target) return true;
else if (matrix[row][col] > target) col--;
else if (matrix[row][col] < target) row++;
}
return false
}