566.重新构建矩阵(javascript)566.ReshapetheMatrix

原创
小哥 3年前 (2022-11-10) 阅读数 10 #大杂烩

在 MATLAB 在中,有一个非常有用的函数。 reshape ,它可以是a。 m x n 矩阵被重塑为另一个不同大小的矩阵(r x c),但保留其原始数据。

给你一个二维数组 mat 表示的 m x n 矩阵和两个正整数 r 和 c ,分别表示要重构的矩阵的行数和列数。

重建的矩阵要求原始矩阵的所有元素都相同。 行遍历顺序 填充。

如果 reshape 如果操作可行且合理,则输出新的重构矩阵。

In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.

You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.

The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

示例 1:

输入:mat = [[1,2],[3,4]], r = 1, c = 4
输出:[[1,2,3,4]]

示例 2:

输入:mat = [[1,2],[3,4]], r = 2, c = 4
输出:[[1,2],[3,4]]

提示:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • -1000 <= mat[i][j] <= 1000
  • 1 <= r, c <= 300

根据问题的含义:
如果 reshape 如果操作可行且合理,则输出新的重构矩阵。

  1. const ans = new Array(r).fill(0).map(() => new Array(c).fill(0)); 塑造一个r行c列,全是0多维数组
  2. 遍历阵列,将列转换为动态,
  3. 行是i / c,列是i % c

参考: leetcode刷题知识点汇总(刷题必备)

var matrixReshape = function (mat, r, c) {
    let list = mat.flat(Infinity)//一维阵列
    let len = list.length
    if (list.length != r * c) {
        return mat
    }
    const ans = new Array(r).fill(0).map(() => new Array(c).fill(0));
    for (let i = 0; i < len; i++) {
        ans[Math.floor(i / c)][i % c] = list[i];
    }
    return ans
};

leetcode: https://leetcode.cn/problems/reshape-the-matrix/

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除