leet-code/reshape-the-matrix/sol_functional.rs

20 lines
687 B
Rust

// This is a more functional solution that I think
// is a bit easier to read, but does iterate over
// the matrix twice (two `Iter.collect()`s). So without
// compiler optimisations it might be a bit slower.
//
// I don't actually know whether this is true or not.
impl Solution {
pub fn matrix_reshape(mat: Vec<Vec<i32>>, r: i32, c: i32) -> Vec<Vec<i32>> {
let (m, n) = (mat.len(), mat[0].len());
if m*n != (r*c) as usize || m == r as usize{
return mat;
}
mat.into_iter()
.flatten()
.collect::<Vec<_>>()
.chunks(c as usize)
.map(|row| row.to_vec())
.collect::<Vec<_>>()
}
}