剑指offer:面试题3、二维数组中的查找

题目描述

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

代码示例

public class Offer3 {
    public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3, 4 },
                {5, 6, 7, 8 },
                {9, 10,11,12},
                {13,14,15,16}
        };
        Offer3 testObj = new Offer3();
        System.out.println(testObj.find(matrix, 6));
        System.out.println(testObj.find(matrix,18));

    }

    public boolean find(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int rows = matrix.length;
        int cols = matrix[0].length;
        int r = 0;
        int c = cols - 1;
        //从右上角开始
        while (r <= rows - 1 && c >= 0) {
            if (target == matrix[r][c]) {
                return true;
            } else if (target > matrix[r][c]) {
                r++;
            } else {
                c--;
            }
        }
        return false;
    }
}

原文地址:https://www.cnblogs.com/ITxiaolei/p/13138663.html