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
| // @lc code=start
impl Solution {
/// ## 解题思路
/// - 二分查找
/// 1. 由于该矩阵的特性,
/// 2. 二分法依次比较target和第0列大小, 找到target处在那一行;
/// 3. 在该行中, 通过二分法查找target是否处于该行中;
pub fn search_matrix(matrix: Vec<Vec<i32>>, target: i32) -> bool {
let (m, n) = (matrix.len(), matrix[0].len());
let (mut l, mut r) = (0, m);
let mut row = 0;
while l < r {
row = (l + r) / 2;
if matrix[row][0] == target || matrix[row][n - 1] == target {
return true;
} else if matrix[row][0] < target {
if matrix[row][n - 1] > target {
break;
}
l = row + 1;
} else {
r = row;
}
}
let (mut l, mut r) = (0, n);
while l < r {
let col = (l + r) / 2;
if matrix[row][col] == target {
return true;
} else if matrix[row][col] < target {
l = col + 1;
} else {
r = col;
}
}
return false;
}
}
// @lc code=end
struct Solution;
|