[leetCode]面试题04.二维数组

暴力法

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

线性查找

ass Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if(matrix == null || matrix.length == 0) return false;
        int rows = matrix.length;
        int cols = matrix[0].length;
        int row = 0;
        int col = cols - 1;
        while(row < rows && col >= 0){
            if(matrix[row][col] < target){
                ++row;
            }else if(matrix[row][col] > target){
                --col;
            }else{
                return true;
            }
        }
        return false;
    }
}
posted @ 2020-07-22 09:22  消灭猕猴桃  阅读(59)  评论(0编辑  收藏  举报