编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。
/** * @param {number[][]} matrix * @param {number} target * @return {boolean} */ const searchMatrix = (matrix, target) => { let mayBeInArray = [] let outerStartIdx = 0, outerEndIdx = matrix.length - 1; while(outerStartIdx <= outerEndIdx){ if(outerStartIdx === outerEndIdx){ mayBeInArray = matrix[outerStartIdx] break } let outerMidIdx = Math.floor((outerStartIdx + outerEndIdx) / 2) if(matrix[outerMidIdx][0] > target){ outerEndIdx = --outerMidIdx }else if(matrix[outerMidIdx][matrix[outerMidIdx].length - 1] < target){ outerStartIdx = ++outerMidIdx }else{ mayBeInArray = matrix[outerMidIdx] break } } let innerStartIdx = 0, innerEndIdx = mayBeInArray.length - 1; while(innerStartIdx <= innerEndIdx){ let innerMidIdx = Math.floor((innerStartIdx + innerEndIdx) / 2) if(mayBeInArray[innerMidIdx] > target){ innerEndIdx = --innerMidIdx }else if(mayBeInArray[innerMidIdx] < target){ innerStartIdx = ++innerMidIdx }else{ return true } } return false };
标签:matrix,mayBeInArray,矩阵,else,二维,搜索,outerMidIdx,target From: https://www.cnblogs.com/zhenjianyu/p/17091551.html