剑指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

题解:
1.确定n,m n=matrix.length m=matrix[0].length, 同时要判断n,m是否介于0~1000之间
2.从二维矩阵的右上角(左移变小,下移变大)开始查找,当前元素等于target则返回true,当前元素小于target则下移,当前元素大于target则左移
也可从左下角开始查找(右移变大,上移变小)
证明:若当前元素num>target,则target必不在当前列,所以可消去当前列,行左移。若当前元素num<target,则target必不在num当前行,所以可消去当前行,列下移。

代码

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
         if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int rows = matrix.length;
        int columns = matrix[0].length;
        int row = 0;
        int column = columns-1;
        int num;
        while(column>=0&&row<rows){
             num =matrix[row][column];
             if(num==target){
                    return true;
                }
                else if(num>target){
                    column--;
                }
                else{
                    row++;
                }
        }
        return false;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章