剑指 Offer 04. 二维数组中的查找 - Touale Cula's Blog

题目内容

在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

 

示例:

现有矩阵 matrix 如下:

1
2
3
4
5
6
7
8
9
10
[
[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。

 

限制:

1
2
3
0 <= n <= 1000

0 <= m <= 1000

解法一:二分法

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 Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
for(vector v:matrix){
if(v.empty()) continue;
if(v[0] > target){
break;
}

if(v[v.size()-1]<target){
continue;
}

int l=0,r=v.size()-1;
while(l<=r){
int m = l+((r-l)>>1);
if(v[m]>target) r = m-1;
else if(v[m]<target) l = m+1;
else return 1;
}
}
return 0;
}
};

结果

1
2
3
4
5
6
7
8
9
10
11
12
执行用时:
16 ms
, 在所有 C++ 提交中击败了
97.15%
的用户
内存消耗:
13.4 MB
, 在所有 C++ 提交中击败了
5.37%
的用户
通过测试用例:
129 / 129

解法二:线性查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {

int row = matrix.size()-1, col = 0;

while(row>=0 && col < matrix[0].size()){
if(matrix[row][col]>target) row--;
else if(matrix[row][col]<target) col++;
else return 1;

}

return 0;

}
};

结果:

1
2
3
4
5
6
7
8
9
10
执行用时:
20 ms
, 在所有 C++ 提交中击败了
80.79%
的用户
内存消耗:
12.8 MB
, 在所有 C++ 提交中击败了
10.13%
的用户