Leetcode 566 Reshape Matrix

Leetcode 566 Reshape Matrix

Title description:

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

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

重构后的矩阵需要将原始矩阵的所有元素以相同的 行遍历顺序 填充。

如果具有给定参数的 reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
Example 1:

insert image description here

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

insert image description here

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

solution:

code:

class Solution {

public:

  vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {

      //mat数组的行数
​    int m = mat.size();
      //mat数组的列数

​    int n = mat[0].size();

​    if(m*n != r*c)

​    {

​      return mat;

​    }

   vector<vector<int>> ans(r, vector<int>(c));

​    for (int x=0;x<m*n;x++)

​    {

​      ans[x/c][x%c]=mat[x/n][x%n];

​    }

​    return ans;

  }

};


Problem-solving ideas:

For a two-dimensional array with m rows, n columns, and row and column subscripts starting from 0, we can map each element (i, j) into the integer field, and they are in row-first order One-to-one corresponds to each integer in [0, mn). Visually speaking, we "flatten" this two-dimensional array into a one-dimensional array.

/ means integer division, % means modulo operation.

Then what the topic requires us to do is equivalent to: mapping the two-dimensional array mat into a one-dimensional array; mapping this one-dimensional array back to a two-dimensional array of r rows and c columns.

We can directly use a one-dimensional array for transition, but we can also get the reshaping matrix of r rows and cc columns directly from the two-dimensional array mat.

Let mat itself be m rows and n columns, if m n != r c, then the number of elements contained in the two is not the same, so reshaping cannot be performed;

Otherwise, for x∈[0,mn), the corresponding subscript of the xth element in mat is (x / n, x % n), and the corresponding subscript in the new reshaping matrix is ​​(x / c ,x % c). We can directly assign values.
Then, for x∈[0,mn), the corresponding subscript of the xth element in mat is (x / n, x % n), and the corresponding subscript in the new reshaping matrix is ​​(x / c ,x % c). We can directly assign values.

Guess you like

Origin blog.csdn.net/Duba_zhou/article/details/124808760