第十题:在行和列都排好序的数组中找数

版权声明:Please make the source marked https://blog.csdn.net/qq_31807385/article/details/86240912

题目要求:

在行和列都排好序的N* M的矩阵Matrix中找数K,也即 判断 K 是否在矩阵Matrix 中例如

0 1 2 5
2 3 4 7
4 4 4 8
5 7 7 9

如果k 为 7 ,返回true, k 为 6 则返回 false,要求时间复杂度为O(M + N)额外空间复杂度为O(1)

代码实现:

package com.isea.brush;

/**
 * 判断行和列都排好序的N * M 的矩阵Matrix中是否含有 元素 k
 * 实现的思路:
 * 从矩阵的左上角角开始出发,判断但提前的元素和 k的大小关系,如果比 k大,则左移;
 * 如果比 k 小,则下移,直达移动到了矩阵的左下角停止,或者是找到了元素停止
 */
public class FindK {
    public static boolean findK(int[][] matrix, int k) {
        int curR = 0;
        int curC = matrix[0].length - 1;
        while (curR < matrix.length && curC > -1) {
            if (matrix[curR][curC] == k) {
                return true;
            } else if (matrix[curR][curC] > k) {
                curC--;
            } else {
                curR++;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[][] matrix = {{0, 1, 2, 5}, {2, 3, 4, 7}, {4, 4, 4, 8}, {5, 7, 7, 9}};
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println(findK(matrix, 7));
        System.out.println(findK(matrix, 6));
    }
    /**
     * 2 3 4 7 
     * 4 4 4 8 
     * 5 7 7 9 
     * true
     * false
     */
}

猜你喜欢

转载自blog.csdn.net/qq_31807385/article/details/86240912