题目
编程语言
rust
注意点
行坐标和列坐标以 列数 为标准
代码
pub fn search_matrix(matrix: Vec<Vec<i32>>, target: i32) -> bool {
let m = matrix.len() as i32;
if m == 0 {
return false;
}
let n = matrix[0].len() as i32;
let mut left = 0_i32;
let mut right = (m * n) - 1;
let mut mid;
let mut mid_x;
let mut mid_y;
while left <= right {
mid = left + ((right - left) >> 1);
mid_x = (mid / n) as usize;
mid_y = (mid % n) as usize;
match matrix[mid_x][mid_y].cmp(&target) {
std::cmp::Ordering::Less => left = mid + 1,
std::cmp::Ordering::Greater => right = mid - 1,
std::cmp::Ordering::Equal => return true,
}
}
false
}
测试
#[cfg(test)]
mod tests{
use super::*;
#[test]
fn test_true(){
assert_eq!(search_matrix(vec![[1,3,5,7].to_vec(),[10,11,16,20].to_vec(),[23,30,34,60].to_vec()],3),true);
}
#[test]
fn test_false(){
assert_eq!(search_matrix(vec![[1,3,5,7].to_vec(),[10,11,16,20].to_vec(),[23,30,34,60].to_vec()],13),false);
}
#[test]
fn test_false1(){
assert_eq!(search_matrix(vec![[1,1].to_vec()],2),false);
}
}