美文网首页算法
排序二维数组中找数

排序二维数组中找数

作者: 一凡呀 | 来源:发表于2017-12-07 09:48 被阅读0次

题目:

image.png

思路:

取右上角的点或者左下角的点作为起始点,因为是排序好的数组,在这里我们取右上角的点作为基本点,如果当前值比查询的值大,说明要找的值在右上角点的左边,如果小,说明在右上角的点下面。

代码:

public static boolean isContains(int[][] matrix, int K) {
        int row = 0;
        int col = matrix[0].length - 1;
        while (row < matrix.length && col > -1) {
            if (matrix[row][col] == K) {
                return true;
            } else if (matrix[row][col] > K) {
                col--;
            } else {
                row++;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[][] matrix = new int[][] { { 0, 1, 2, 3, 4, 5, 6 },// 0
                { 10, 12, 13, 15, 16, 17, 18 },// 1
                { 23, 24, 25, 26, 27, 28, 29 },// 2
                { 44, 45, 46, 47, 48, 49, 50 },// 3
                { 65, 66, 67, 68, 69, 70, 71 },// 4
                { 96, 97, 98, 99, 100, 111, 122 },// 5
                { 166, 176, 186, 187, 190, 195, 200 },// 6
                { 233, 243, 321, 341, 356, 370, 380 } // 7
        };
        int K = 233;
        System.out.println(isContains(matrix, K));
    }

相关文章

网友评论

    本文标题:排序二维数组中找数

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