-
Notifications
You must be signed in to change notification settings - Fork 0
/
0074. 搜索二维矩阵
46 lines (41 loc) · 1.01 KB
/
0074. 搜索二维矩阵
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// 二分法
1074. 搜索二维矩阵
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。
示例 1:
输入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
输出: true
示例 2:
输入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
输出: false
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty()) return false;
int m = matrix.size(), n = matrix[0].size(), l = 0, r = m*n-1;
while(l <= r){
int mid = (l + r) >> 1;
int x = matrix[mid/n][mid%n];
if(x == target) return true;
if(x <target)
l = mid + 1;
else
r = mid - 1;
}
return false;
}
};