二维数组中的查找

138 阅读1分钟

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

| 暴力法

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        int rows = matrix.length;
        int cols = 0;
        if(rows != 0) {
            cols = matrix[0].length;
        }
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < cols; j++) {
                if(target == matrix[i][j]) {
                    return true;
                }
            }
        }
        return false;
    }
}

时间复杂度:O(N^2)
空间复杂度:O(1)

| 线性查找法

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int rowIndex = 0;
        int colIndex = matrix[0].length - 1;
        // start from matrix[0][m-1] 
        while(rowIndex >= 0 && colIndex >= 0 && rowIndex < matrix.length 
        && colIndex < matrix[0].length ) {
            if(target == matrix[rowIndex][colIndex]) {
                return true;
            } else if(target < matrix[rowIndex][colIndex]) {
                colIndex--;
            } else {
                rowIndex++;
            }
        }
        return false;
        
    }
}