0%

搜索二维矩阵

题目

给定一个 M * N 的矩阵, 矩阵中每一行从左到右依次递增, 每一列从上到下依次递增, 判断矩阵中是否含有整数K.

矩阵示例

1
2
3
0, 1, 2, 3, 4,
2, 3, 4, 5, 6,
6, 7, 8, 9, 10

要求

时间复杂度为 O(M + N) , 空间复杂度为 O(1)

题解

可先选取左下角或右上角处的元素进行比较, 每次移动时, 均只有两种可能的移动方向. 每次查找最多横向比较 N 次, 纵向比较 M 次, 故时间复杂度为 O(M + N)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    /**
* 本例从右上角处元素开始比较
* @param matrix 输入矩阵
* @param target 目标数值
* @return 是否含有该数值
*/
public class SearchMatrix {
public static boolean searchMatrix(int[][] matrix, int target) {
int M = 0;
if (matrix.length == 0)
return false;

int N = matrix[0].length - 1;

int cuR = M;
int cuC = N;

while (cuR < matrix.length && cuC >= 0) {
if (matrix[cuR][cuC] > target)
cuC--;
else if (matrix[cuR][cuC] < target)
cuR++;
else {
return true;
}
}

return false;
}
}

例题: LeetCode # 74

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。
示例:

输入:

1
2
3
4
5
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
1
target = 3

输出: true

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class SearchMatrix {
public boolean searchMatrix(int[][] matrix, int target) {
int M = 0;
if (matrix.length == 0)
return false;

int N = matrix[0].length - 1;

int cuR = M;
int cuC = N;

while (cuR < matrix.length && cuC >= 0) {
if (matrix[cuR][cuC] > target)
cuC--;
else if (matrix[cuR][cuC] < target)
cuR++;
else {
return true;
}
}

return false;
}
}

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class SearchMatrix:
"""
本例从右上角元素开始比较
:param matrix: 输入矩阵
:param target: 目标数值
:return: 是否含有该数值
"""
def search_matrix(self, matrix, target):
M = 0
if len(matrix) == 0:
return False

N = len(matrix[0]) - 1

cuR = M
cuC = N

while cuR < len(matrix) and cuC >= 0:
if matrix[cuR][cuC] > target:
cuC -= 1
elif matrix[cuR][cuC] < target:
cuR += 1
else:
return True

return False