JZ4 二维数组中的查找
描述
在一个二维数组array中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
[
[1,2,8,9],
[2,4,9,12],
[4,7,10,13],
[6,8,11,15]
[2,4,9,12],
[4,7,10,13],
[6,8,11,15]
]
给定 target = 7,返回 true。
给定 target = 3,返回 false。
数据范围:矩阵的长宽满足 0 \le n,m \le 5000≤n,m≤500 , 矩阵中的值满足 0 \le val \le 10^90≤val≤109
进阶:空间复杂度 O(1)O(1) ,时间复杂度 O(n+m)O(n+m)
进阶:空间复杂度 O(1)O(1) ,时间复杂度 O(n+m)O(n+m)
示例1
输入:
7,[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
返回值:
true
说明:存在7,返回true
目录结构:
src
- main.rc
- solution.rc
// solution.rc
// 不写mod solution
pub struct vec2d{
}
impl vec2d {
pub fn new() -> Self {
vec2d{}
}
pub fn find(&self, target: i32, array: Vec<Vec<i32>>) -> bool {
// write code here
if array.len() == 0 || array[0].len() == 0 {
return false;
}
let row_len = array.len() - 1;
let col_len = array[0].len() - 1;
let mut i:usize= row_len;
let mut j:usize = 0;
while i as i32 >= 0 && j <= col_len {
if array[i][j] > target {
i = i - 1;
} else if array[i][j] < target {
j = j + 1;
} else {
return true;
}
}
return false;
}
}
mod solution;
use self::solution::vec2d;
fn main() {
let solution:vec2d = vec2d::new();
let target:i32 = 10;
let array:Vec<Vec<i32>> = vec![
vec![1,2,8,9],
vec![2,4,9,12],
vec![4,7,10,13],
vec![6,8,11,15]
];
let res:bool = solution.find(target, array);
match res {
true => println!("find the number!"),
false => println!("not find the number"),
}
}

浙公网安备 33010602011771号