Skip to content

Commit a12e2ef

Browse files
authored
Merge pull request neetcode-gh#1986 from nirajvenkat/patch-5
Create 0074-search-a-2d-matrix.rs
2 parents fc5ea09 + 4f92246 commit a12e2ef

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

rust/0074-search-a-2d-matrix.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
use std::cmp::Ordering::{Equal, Less, Greater};
2+
3+
impl Solution {
4+
pub fn search_matrix(matrix: Vec<Vec<i32>>, target: i32) -> bool {
5+
let (mut t, mut b) = (0, matrix.len());
6+
let mut row = 0;
7+
while t < b {
8+
row = t + (b - t) / 2;
9+
let first = matrix[row][0];
10+
let last = *matrix[row].last().unwrap();
11+
if target == first || target == last {
12+
return true;
13+
} else if target < first {
14+
b = row;
15+
} else if target > last {
16+
t = row + 1;
17+
} else {
18+
break;
19+
}
20+
}
21+
22+
if t > b {
23+
return false;
24+
}
25+
26+
let (mut l, mut r) = (0, matrix[row].len());
27+
while l < r {
28+
let col = l + (r - l) / 2;
29+
match target.cmp(&matrix[row][col]) {
30+
Equal => return true,
31+
Less => r = col,
32+
Greater => l = col + 1
33+
}
34+
}
35+
36+
false
37+
}
38+
}

0 commit comments

Comments
 (0)