美文网首页
【剑指Offer 3】二维数组中的查找

【剑指Offer 3】二维数组中的查找

作者: 3e1094b2ef7b | 来源:发表于2017-06-30 08:12 被阅读11次

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

Java代码如下:

package demo;

public class TestMatrix {
    public static boolean find(int[][] matrix, int number) {
        if(matrix == null) {
            return false;
        }
        int rows = matrix.length;
        int cols = matrix[0].length;
        if(rows < 1 || cols < 1) {
            return false;
        }
        int row = 0;
        int col = cols - 1;
        while(row >= 0 && row < rows && col >= 0 && col < cols) {
            if(matrix[row][col] == number) {
                return true;
            } else if(matrix[row][col] > number) {
                col--;
            } else {
                row++;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 8, 9},
                {2, 4, 9, 12},
                {4, 7, 10, 13},
                {6, 8, 11 ,15}
        };
    
        System.out.println(find(matrix, 7)); // 在数组中,介于最大值与最小值中间
        System.out.println(find(matrix, 15)); // 在数组中,最大值
        System.out.println(find(matrix, 1)); // 在数组中,最小值
        System.out.println(find(matrix, 5)); // 不在数组中,介于最大值与最小值中间
        System.out.println(find(matrix, 20)); // 不在数组中,比最大值还大
        System.out.println(find(matrix, 0)); // 不在数组中,比最小值还小
        System.out.println(find(null, 7)); // 健壮性测试,输入空指针
    
    }
}
运行结果

来源:http://blog.csdn.net/derrantcm/article/details/45330789

相关文章

网友评论

      本文标题:【剑指Offer 3】二维数组中的查找

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