566. 重塑矩阵
在MATLAB中,有一个非常有用的函数 reshape
,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。
给出一个由二维数组表示的矩阵,以及两个正整数r
和c
,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。
如果具有给定参数的reshape
操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
示例 1:
输入: nums = [[1,2], [3,4]] r = 1, c = 4 输出: [[1,2,3,4]] 解释: 行遍历nums的结果是 [1,2,3,4]。新的矩阵是 1 * 4 矩阵, 用之前的元素值一行一行填充新矩阵。
示例 2:
输入: nums = [[1,2], [3,4]] r = 2, c = 4 输出: [[1,2], [3,4]] 解释: 没有办法将 2 * 2 矩阵转化为 2 * 4 矩阵。 所以输出原矩阵。
注意:
给定矩阵的宽和高范围在 [1, 100]。
给定的 r 和 c 都是正数。
C
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *columnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** matrixReshape(int** nums, int numsRowSize, int numsColSize, int r, int c, int** columnSizes, int* returnSize)
{
int m=numsRowSize;
int n=numsColSize;
if(m*n!=r*c)
{
*returnSize=m;
*columnSizes=(int*)malloc(sizeof(int)*m);
for(int i=0;i<m;i++)
{
(*columnSizes)[i]=n;
}
return nums;
}
else
{
int** res=(int**)malloc(sizeof(int*)*r);
*columnSizes=(int*)malloc(sizeof(int)*r);
int* temp=malloc(sizeof(int)*r*c);
int count=0;
*returnSize=r;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
temp[count++]=nums[i][j];
}
}
count=0;
for(int i=0;i<r;i++)
{
res[i]=(int*)malloc(sizeof(int)*c);
for(int j=0;j<c;j++)
{
res[i][j]=temp[count++];
}
(*columnSizes)[i]=c;
}
return res;
}
}
C++
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c)
{
int m=nums.size();
int n=nums[0].size();
vector<vector<int>> res(r,vector<int>(c));
vector<int> temp(m*n,0);
int count=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
temp[count++]=nums[i][j];
}
}
if(m*n!=r*c)
{
return nums;
}
else
{
count=0;
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
res[i][j]=temp[count++];
}
}
}
return res;
}
};
python
class Solution:
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
m=len(nums)
n=len(nums[0])
temp=[]
res=[[0 for i in range(c)] for j in range(r)]
if m*n!=r*c:
return nums
else:
for i in range(m):
for j in range(n):
temp.append(nums[i][j])
for i in range(r):
for j in range(c):
res[i][j]=temp[0]
del temp[0]
return res