-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0074_search_a_2d_matrix.rs
More file actions
53 lines (49 loc) · 1.47 KB
/
s0074_search_a_2d_matrix.rs
File metadata and controls
53 lines (49 loc) · 1.47 KB
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
47
48
49
50
51
52
53
#![allow(unused)]
pub struct Solution {}
impl Solution {
// O(log(mn)) O(1)
fn search_matrix(matrix: Vec<Vec<i32>>, target: i32) -> bool {
if matrix.is_empty() || matrix[0].is_empty() {
return false;
}
let (m, n) = (matrix.len(), matrix[0].len());
let (mut start, mut end) = (0, m * n - 1);
while start + 1 < end {
let mid = start + (end - start) / 2;
let (i, j) = (mid / n, mid % n);
if matrix[i][j] < target {
start = mid;
} else if matrix[i][j] > target {
end = mid;
} else {
return true;
}
}
matrix[start / n][start % n] == target || matrix[end / n][end % n] == target
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_74() {
// show stdout message
//$: cargo t -- --test-threads=1 --nocapture
assert_eq!(
Solution::search_matrix(
vec![vec![1, 3, 5, 7], vec![10, 11, 16, 20], vec![23, 30, 34, 50]],
3
),
true
);
assert_eq!(
Solution::search_matrix(
vec![vec![1, 3, 5, 7], vec![10, 11, 16, 20], vec![23, 30, 34, 50]],
13
),
false
);
assert_eq!(Solution::search_matrix(Vec::<Vec<i32>>::new(), 0), false);
assert_eq!(Solution::search_matrix(vec![vec![1]], 0), false);
}
}