美文网首页
240. 搜索二维矩阵 II

240. 搜索二维矩阵 II

作者: justonemoretry | 来源:发表于2021-09-08 23:07 被阅读0次
image.png

解法

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        // 选点左下角,小于target则右移,大于target则上移
        // 有种二叉查找树的感觉,每个节点的上方小于自己,像左节点
        // 下方大于自己,像右节点
        int row = matrix.length - 1;
        int col = 0;
        // 不越界的情况进行移动
        while (row >= 0 && col <= matrix[0].length - 1) {
            if (matrix[row][col] > target) {
                // 大于,向上移,上面元素更小
                row--;
            } else if (matrix[row][col] < target) {
                // 小于,向右移,
                col++;
            } else {
                return true;
            }
        }
        return false;
    }
}

相关文章

网友评论

      本文标题:240. 搜索二维矩阵 II

      本文链接:https://www.haomeiwen.com/subject/firlwltx.html