搜索二维矩阵 II

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:

每行的元素从左到右升序排列。 每列的元素从上到下升序排列。 示例:

现有矩阵 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。

给定 target = 20,返回 false。

思路一:
是自己的思路。难道说我现在已经可以做到自己把题做出来的水平了?🤔
因为收到二分查找的启发,所以我的思路是:每次都找二维数组的中心位置,然后判断它和target的关系,由于中心点的左上方一定比它小,右下方一定比它大。所以每次都能缩小一定空间,然后不停递归,当数组只有一个数就判断它的大小是否等于目标值。
时间复杂度:O(mnlogmn)
空间复杂度:O(1)

class Solution {
    int[][] matrix;
    int target;
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix.length==0 || matrix[0].length==0)    return false;
        this.matrix = matrix;
        this.target = target;
        return searchChild(0,matrix.length-1,0,matrix[0].length-1);
    }
    public boolean searchChild(int rl,int rh,int cl,int ch){
        if(rl==rh && cl==ch){
            return matrix[rl][ch]==target;
        }
        int r = (rl+rh)/2;
        int c = (cl+ch)/2;
        if(matrix[r][c]==target){
            return true;
        }
        if(matrix[r][c]<target){
            boolean down = false;
            if(r<rh)   down = searchChild(r+1,rh,cl,ch);
            boolean right = false;
            if(c<ch)    right =searchChild(rl,r,c+1,ch);
            return down || right;
        }
        if(matrix[r][c]>target){
            boolean up = false;
            if(r>rl)    up = searchChild(rl,r-1,cl,ch);
            boolean left = false;
            if(c>cl)    left = searchChild(r,rh,cl,c-1);
            return up || left;
        }
        return false;
    }
}

思路二:
逐渐逼近。
以右上角作为起点,比较当前值与target的大小。如果当前值更大,那就向左走;如果当前值更小,那就向下走;相等就返回true。
这样的优点是简单,而且耗时比我的还短。。。

  • 时间复杂度:O(n+m)。时间复杂度分析的关键是注意到在每次迭代(我们不返回 true)时,行或列都会精确地递减/递增一次。由于行只能减少 m 次,而列只能增加 n 次,因此在导致 while 循环终止之前,循环不能运行超过 n+m次。因为所有其他的工作都是常数,所以总的时间复杂度在矩阵维数之和中是线性的。
  • 空间复杂度:O(1)。
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0) return false;
        int m = 0;
        int n = matrix[0].length - 1;
        while (m < matrix.length && n >= 0) {
            if (matrix[m][n] == target) {
                return true;
            } else if (matrix[m][n] > target) {
                n--;
            } else {
                m++;
            }
        }
        return false;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值