-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0074-search-a-2d-matrix.rs
38 lines (34 loc) · 1 KB
/
0074-search-a-2d-matrix.rs
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
use std::cmp::Ordering::{Equal, Less, Greater};
impl Solution {
pub fn search_matrix(matrix: Vec<Vec<i32>>, target: i32) -> bool {
let (mut t, mut b) = (0, matrix.len());
let mut row = 0;
while t < b {
row = t + (b - t) / 2;
let first = matrix[row][0];
let last = *matrix[row].last().unwrap();
if target == first || target == last {
return true;
} else if target < first {
b = row;
} else if target > last {
t = row + 1;
} else {
break;
}
}
if t > b {
return false;
}
let (mut l, mut r) = (0, matrix[row].len());
while l < r {
let col = l + (r - l) / 2;
match target.cmp(&matrix[row][col]) {
Equal => return true,
Less => r = col,
Greater => l = col + 1
}
}
false
}
}