剑指 Offer 04. 二维数组中的查找

在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

示例:

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

限制:

0 <= n <= 1000

0 <= m <= 1000

我的解答:

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        int height = matrix.length-1;
        int j = 0;
        while(height >= 0 && j < matrix[0].length) {
            if (matrix[height][j] < target){
                j++;
            }else if (matrix[height][j] > target){
                height--;
            }else {
                return true;
            }
        }
        return false;
    }
}

这道题在解答时,想的是利用i,j的值,通过依次比较遍历的数,然后对i,j进行加减,不过我这种方法会导致已经遍历过的数再次被遍历到,不能做到排除已经遍历的数的作用。无果后,看了解题思路后,自己尝试写了测试代码。

leetcode解析:

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        int i = matrix.length - 1, j = 0;
        while(i >= 0 && j < matrix[0].length)
        {
            if(matrix[i][j] > target) i--;
            else if(matrix[i][j] < target) j++;
            else return true;
        }
        return false;
    }
}

作者:jyd

链接:https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/solution/mian-shi-ti-04-er-wei-shu-zu-zhong-de-cha-zhao-zuo/

来源:力扣(LeetCode)

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

posted @ 2021-03-02 20:35  锖兔真菰  阅读(48)  评论(0编辑  收藏  举报