原题:剑指 Offer 04. 二维数组中的查找
https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix.length == 0 || matrix[0].length == 0 || matrix == null) {//不要只考虑matrix.length == 0
return false;
}
int n = 0 , m = matrix[0].length - 1;
while(n <= matrix.length - 1 && m >= 0){
int n = matrix[n][m];//这里用一个n保存matrix[n][m],后面就不用每次都去数组里取了
if(n > target){
m--;
}
else if(n < target){
n++;
}
else return true;
}
return false;
}
}
核心算法:
二叉搜索树查询。其实左下角也是二叉搜索树根节点。
本文解析如何利用二叉搜索树思想简化二维数组中查找操作,通过实例代码展示如何避免重复计算,提高查找效率。核心算法利用矩阵左下角作为二叉搜索树的根节点,优化查找过程。
686

被折叠的 条评论
为什么被折叠?



