方法一:通过每一次比较当前所剩区域的右上角和目标值的大小来进行判断
- 如果右上角的元素等于target,返回true
- 如果右上角的元素小于target,删除右上角元素所在的行 row++
- 如果右上角的元素大于target,删除右上角元素所在的列 col–
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix.length == 0||matrix[0].length == 0||matrix == null){
return false;
}
//根据二维数组的特性,每次选取剩余二维数组的右上角和目标元素进行大小比较
//如果右上角的元素等于target,返回true
//如果右上角的元素小于target,删除右上角元素所在的行
//如果右上角的元素大于target,删除右上角元素所在的列
int rows = matrix.length;
int cols = matrix[0].length;
int row = 0,col = cols-1;
while(row < rows && col >= 0){
if(matrix[row][col] < target){
row = row + 1; //删除所在的行
}
else if(matrix[row][col] > target){
col= col - 1; //删除所在的列
}
else{
return true;
}
}
return false;
}
}
时间复杂度:O(n+m),访问到下标的行最多为n,访问到下标的列最多为m
空间复杂度:O(1)
和这种方法类似的还可以从二维数组的左下角开始,当当前值大于目标值,向上方寻找,当当前的值小于目标值,向右方寻找.
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0|| matrix[0].length==0){
return false;
}
int rows = matrix.length,cols = matrix[0].length;
int row = rows-1,col = 0;
while(row >=0 && col<cols){
int cur = matrix[row][col];
if(cur == target){
return true;
}else if(cur < target){
col++;
}else if(cur > target){
row--;
}
}
return false;
}
}
时间复杂度O(n+m)
空间复杂度O(1)
方法二:暴力,这个方法就没什么好说的了,双重for循环
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int rows = matrix.length, columns = matrix[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (matrix[i][j] == target) {
return true;
}
}
}
return false;
}
}
时间复杂度:O(nm),双重for循环
空间复杂度:O(1)