reshape-the-matrix
This commit is contained in:
parent
c85bf9b307
commit
365cacbd42
|
@ -0,0 +1,20 @@
|
||||||
|
// 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<_>>()
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
// A solution using loops and still pretty
|
||||||
|
// easy to understand, and iterates over the
|
||||||
|
// matrix only once.
|
||||||
|
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());
|
||||||
|
let (r, c) = (r as usize, c as usize);
|
||||||
|
if m*n != r*c || m == r {
|
||||||
|
return mat;
|
||||||
|
}
|
||||||
|
let mut reshaped_matrix = vec![vec![0; c]; r];
|
||||||
|
for idx in (0..m*n) {
|
||||||
|
reshaped_matrix[idx / c][idx % c] = mat[idx / n][idx % n];
|
||||||
|
}
|
||||||
|
reshaped_matrix
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue