[JavaScript 刷题] 矩阵 - 重塑矩阵, leetcode 566

[JavaScript 刷题] 矩阵 - 重塑矩阵, leetcode 566

github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。

题目地址:566. 重塑矩阵

题目

如下:

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.

解题思路

这道题就是将矩阵 A 变为矩阵 B,基本上没有什么难度。

主要就是在于一个条件,那就是矩阵 A 是不是能转变为矩阵 B,比如说一个 2x3 的矩阵就没有办法转换成一个 1x5 的矩阵。

随后就是遍历矩阵,将值推进新的二维数组即可。

还有一个比较省空间的做法是直接在原有的数组上进行操作,这样细分也有两种处理方法:

  1. 用另外的变量计算一下原有的长宽
  2. 使用 % 去计算现有的长宽

使用 JavaScript 解题

这里的处理方式还是用比较粗暴的方式去解的,毕竟要求说需要返回一个新的数组,在大 O 差不多的情况下,就挑简单的做了。

/**
 * @param {number[][]} mat
 * @param {number} r
 * @param {number} c
 * @return {number[][]}
 */
var matrixReshape = function (mat, r, c) {
    
    
  const maxRow = mat.length,
    maxCol = mat[0].length;
  if (r * c !== maxRow * maxCol) return mat;

  const newMat = [];
  let matR = 0,
    matC = 0,
    counter = 0;

  while (counter < r * c) {
    
    
    const arr = [];
    for (let i = 0; i < c; i++) {
    
    
      if (matC === maxCol) {
    
    
        matC = 0;
        matR++;
      }
      arr.push(mat[matR][matC++]);
      counter++;
    }

    newMat.push(arr);
  }

  return newMat;
};

猜你喜欢

转载自blog.csdn.net/weixin_42938619/article/details/125148345