暴力法
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;
}
}