LeetCode566 Reshape the Matrix

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

In MATLAB, there is a very useful function called ‘reshape’, which can reshape a matrix into a new one with different size but keep its original data.

You’re given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to 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.

Note:

  1. The height and width of the given matrix is in range [1, 100].
  2. The given r and c are all positive.

样例

1
2
3
4
5
6
7
8
9
Input: 
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
1
2
3
4
5
6
7
8
9
10
Input: 
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.

思路

给定一个二维数组,模拟 MATLAB 中 reshape 函数的操作,若无法完成,则输出原数组

题中要求元素以row-traversing顺序访问,则$r$行$n$列的二维数组第$i$个访问到的元素所在的位置为($i / c$, $i \% c$)

利用这一关系,可以得到从原数组$nums$($n$行$m$列)reshape成 新数组$vec$($r$行$c$列)后的位置关系,$vec[i / c][i \% c] = nums[i / m][i \% m]$

代码

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
int n = nums.size(), m = nums[0].size();
// 元素数量不匹配,reshape失败
if (n * m != r * c) return nums;
// 初始化二维vector
vector<vector<int>> vec(r, vector<int>(c));
for (int i = 0; i < r * c; ++i) vec[i / c][i % c] = nums[i / m][i % m];
return vec;
}
};
分享到 评论