forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request neetcode-gh#1986 from nirajvenkat/patch-5
Create 0074-search-a-2d-matrix.rs
- Loading branch information
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |