题目
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.
Example 1:
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.
Example 2:
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.
Note:
- The height and width of the given matrix is in range [1, 100].
- The given r and c are all positive.
题意
实Matlab中的"reshape"方法,将矩阵转化为一个新的矩阵,并保持原有的数据。
分析及解答
- 【矩阵转换前提】假设转换前矩阵有m行、n列,而转换之后的矩阵有 r 行 、c 列。能够完成转换的条件是 : m * n == r * c
- 【转换公式】因为题目要求,按照原矩阵次序在新矩阵中分配下标,所以新矩阵与原矩阵的下标存在某种映射关系,该部分的目标是找到那种映射关系。
- 【新旧下标映射】 假设在旧矩阵中某个数的行下标为 i ,列 下标为 j 。我们尝试将旧矩阵拉成一行的数组,数组下标为pos,于是得到 pos = i * n + j ;借助一行的数组,转换到新的矩阵,假设新矩阵中新的行标为 p ,列标 为 q ,于是得到 p = pos / c ; q = pos % c; ( 总体思路见图1)
图1:
public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int originR = nums.length;
int originC = nums[0].length;
if(originR * originC != r * c) {
return nums;
}
int[][] newNums = new int[r][c];
int originPos = 0;
for(int i = 0 ; i < originR; i++){
for(int j = 0;j < originC;j++){
originPos = i * originC + j;
newNums[originPos/c][originPos%c] = nums[i][j];
}
}
return newNums;
}
}