在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,
判断数组中是否含有该整数。
示例:
现有矩阵 matrix 如下:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
给定 target = 5,返回 true。
给定 target = 20,返回 false。
限制:
0 <= n <= 1000
0 <= m <= 1000
Related Topics 数组 双指针
解法思路1:
暴力解法:直接循环遍历这个二维数组,如果有这个值直接返回true,否则返回false
Java
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
for (int i = 0; i < matrix.length; i++) {
for (int j =0 ; j < matrix[i].length; j++) {
if (target == matrix[i][j]) {
return true;
}
}
}
return false;
}
}
时间复杂度O(nm):需要遍历二维数组
空间复杂度O(1): 无需额外的空间
Python
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if (matrix[i][j] == target):
return True
return False
解法思路2:
- 因为矩阵的每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
- 从右上角开始遍历,判断比较当前右上角的值与target的值,如果右上角的值大于target,就删除列;如果小于target,删除行
Java
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
// 防止matrix = null 或者 matrix = [] 或者 matrix=[[]]
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int rows = matrix.length;
int columns = matrix[0].length;
int row = 0;
int column = columns - 1;
while (row < rows && column >= 0) {
if (matrix[row][column] == target) {
return true;
} else if (matrix[row][column] > target) {
column--;
} else {
row++;
}
}
return false;
}
}
时间复杂度O(n + m): 列最多减少n次,行最多增加m次
空间复杂度O(1)
Python
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
if (matrix == None or len(matrix) == 0 or len(matrix[0]) == 0):
return False
rows = len(matrix)
columns = len(matrix[0])
row = 0
column = columns - 1
while row < rows and column >= 0:
if matrix[row][column] == target:
return True
elif matrix[row][column] > target:
column -= 1
else:
row += 1
return False