一、题目描述:
leetcode-cn.com/problems/se… 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
- 每行的元素从左到右升序排列。
- 每列的元素从上到下升序排列。
****示例 1:
输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
输出:true
二、思路分析:
- 分治算法
- 我们通过中间数(行中间,列中间)将 matrix 分成四个部分,舍弃掉左上角或者右下角一定不存在答案的部分,递归的算其余三个部分,中间数和target比较判断来舍弃那个区域。
三、AC 代码:超时(python一样的思路可ac)
/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
var searchMatrix = function(matrix, target) {
const recursive = (topLeftX,topLeftY,bottomRightX,bottomRightY)=>{
if( bottomRightX >= matrix[0].length || bottomRightY >= matrix.length || topLeftX > bottomRightX || topLeftY > bottomRightY){
return false
}
if(topLeftY - bottomRightY === 0 && bottomRightX - topLeftX === 0){
return matrix[topLeftY][topLeftX] === target
}
const middleX = Math.floor((bottomRightX + topLeftX) / 2)
const middleY = Math.floor((topLeftY + bottomRightY) / 2)
let remain
if(matrix[middleY][middleX] === target){
return true
}
if(matrix[middleY][middleX] > target){
// 取左上角
remain = recursive(topLeftX,topLeftY,middleX,middleY)
}else{
remain = recursive(middleX+1,middleY+1,bottomRightX,bottomRightY)
// 取右下角
}
const topRightRes = recursive(middleX+1,topLeftY,bottomRightX,middleY)
const bottomLeftRes = recursive(topLeftX,middleY+1,middleX,bottomRightY)
return remain || topRightRes || bottomLeftRes
}
return recursive(0,0,matrix[0].length-1,matrix.length-1)
};
四、总结:
- 通过找二维矩阵的中间数,来舍弃到多余的部分,直到最后子矩阵为一个值。来达到分治的目的。
- 一维数组的二分法也是基于这个思路
本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情