3567. 子矩阵的最小绝对差
This commit is contained in:
parent
bb6a7dc773
commit
b0641080b5
68
src/main.rs
68
src/main.rs
|
|
@ -1,53 +1,29 @@
|
|||
use std::cmp::min;
|
||||
|
||||
struct Solution;
|
||||
mod arr;
|
||||
impl Solution {
|
||||
pub fn number_of_submatrices(mut grid: Vec<Vec<char>>) -> i32 {
|
||||
let mut arr = vec![vec![(0, 0); grid[0].len()]; grid.len()];
|
||||
match grid[0][0] {
|
||||
'.' => arr[0][0] = (0, 0),
|
||||
'X' => arr[0][0] = (0, 1),
|
||||
'Y' => arr[0][0] = (1, 0),
|
||||
_ => {}
|
||||
}
|
||||
let mut ans = 0;
|
||||
for i in 1..grid[0].len() {
|
||||
let (mut y, mut x) = arr[0][i - 1];
|
||||
match grid[0][i] {
|
||||
'X' => x += 1,
|
||||
'Y' => y += 1,
|
||||
_ => {}
|
||||
}
|
||||
if x == y && x != 0 {
|
||||
ans += 1;
|
||||
}
|
||||
arr[0][i] = (y, x)
|
||||
}
|
||||
|
||||
for i in 1..grid.len() {
|
||||
let (mut y, mut x) = arr[i - 1][0];
|
||||
match grid[i][0] {
|
||||
'X' => x += 1,
|
||||
'Y' => y += 1,
|
||||
_ => {}
|
||||
}
|
||||
arr[i][0] = (y, x);
|
||||
if x == y && x != 0 {
|
||||
ans += 1;
|
||||
}
|
||||
for j in 1..grid[i].len() {
|
||||
let (ya, xa) = arr[i - 1][j];
|
||||
let (yb, xb) = arr[i][j - 1];
|
||||
let (yc, xc) = arr[i - 1][j - 1];
|
||||
let (mut x, mut y) = (xa + xb - xc, ya + yb - yc);
|
||||
match grid[i][j] {
|
||||
'X' => x += 1,
|
||||
'Y' => y += 1,
|
||||
_ => {}
|
||||
pub fn min_abs_diff(grid: Vec<Vec<i32>>, k: i32) -> Vec<Vec<i32>> {
|
||||
let k = k as usize;
|
||||
let mut ans = vec![vec![0; grid[0].len()-k+1]; grid.len()-k+1];
|
||||
for i in 0..grid.len() - k+1 {
|
||||
for j in 0..grid[i].len() - k+1 {
|
||||
let mut arr = Vec::<i32>::with_capacity(k*k);
|
||||
for l in 0..k {
|
||||
for m in 0..k {
|
||||
let val = grid[i+l][j+m];
|
||||
arr.push(val);
|
||||
}
|
||||
}
|
||||
if x == y && x != 0 {
|
||||
ans += 1;
|
||||
arr.sort_unstable();
|
||||
let mut val = 1e9 as i32;
|
||||
for i in 1..arr.len() {
|
||||
if arr[i-1] == arr[i] {
|
||||
continue;
|
||||
}
|
||||
val = min(val,(arr[i]-arr[i-1]).abs());
|
||||
}
|
||||
arr[i][j] = (y, x);
|
||||
ans[i][j] = if val == 1e9 as i32 { 0 } else { val };
|
||||
}
|
||||
}
|
||||
ans
|
||||
|
|
@ -55,6 +31,6 @@ impl Solution {
|
|||
}
|
||||
|
||||
fn main() {
|
||||
let result = Solution::number_of_submatrices(arr::make_char_matrix(r#"[["X","Y"],["X","Y"]]"#));
|
||||
let result = Solution::min_abs_diff(arr::make_matrix(r#"[[1,8],[3,-2]]"#), 2);
|
||||
println!("{:?}", result);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue