【剑指Offer编程题】二维数组中的查找 - JAVA

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Katherine_java/article/details/84822125

问题:

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

思路:

该二维数组(矩阵),从左下角来看,左至右递增,下至上递减。

因此我们从左下角遍历,小于目标数则找寻更大的,向右;大于目标数则找寻更小的,向上。

找到直接返回true;超出边界后则未找到,返回false。


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

    public static void main(String[] args) {
        Main main = new Main();

        int[][] array = {{1, 2, 3}, {4, 5, 6}};
        int t = 4;
        System.out.println(main.Find(4, array));
        System.out.println("Hello World!");
    }

    /**
     * 1.遍历方法:最直观的方法
     * 时间复杂度:O(n^2)
     * @param target
     * @param array
     * @return
     */
    public boolean Find1(int target, int[][] array) {
        int rows = array.length;
        int cols = array[0].length;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (array[i][j] == target)
                    return true;
            }
        }
        return false;
    }

    /**
     * 2.从左下角开始搜索
     * 时间复杂度:
     * 若小于该数字,列数右移
     * 若大于该数字,行数上移
     * 时间复杂度:O(n)
     * @param target
     * @param array
     * @return
     */
    public boolean Find(int target, int[][] array) {
        int rows = array.length;
        int cols = array[0].length;
        int row = rows - 1;
        int col = 0;
        while (col <= cols - 1 && row >= 0) {
            if (target == array[row][col])
                return true;
            else if (array[row][col] < target)
                col++; //遍历的数字小于该target数,则找寻更大数,列数右移
            else
                row--;//遍历的数字大于该target数,则找寻更小数,行数上移
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/Katherine_java/article/details/84822125