Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1986 from nirajvenkat/patch-5
Browse files Browse the repository at this point in the history
Create 0074-search-a-2d-matrix.rs
  • Loading branch information
tahsintunan authored Jan 11, 2023
2 parents fc5ea09 + 4f92246 commit a12e2ef
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions rust/0074-search-a-2d-matrix.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,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
}
}

0 comments on commit a12e2ef

Please sign in to comment.