Reshape the Matrix
描述:
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.
Example1:
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.
Example2:
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:
1.The height and width of the given matrix is in range [1, 100].
2.The given r and c are all positive.
思路:
思路很简单啊,就是把二维数组捋直变成一维的,再按照新二维数组的要求放进去。
问题:
但是我这个垃圾被卡了四天,因为我读不懂题目。我就是没看明白这个** columnSizes和* returnSize是来干嘛的有什么用,现在即使accepted了我也不懂,当然最后也还是根据discuss修改了才成功的。按注释里的意思应该是返回一个包含* returnSize个数组的数组,即* returnSize应该是行值,并且这些数组的大小被返回成 * columnSizes数组(所以说不就是c嘛,每个数组都是c啊)。
并且看到二级指针很懵,看了蛮久二级指针和数组指针相关的东西,指针确实是难orz。感觉把columnSizes作为二级指针应该是要对主函数中的指针做修改,单纯传一级指针无法做到只能是传递二级指针,这样?
如何用二级指针建立二位数据并赋值确实是第一次接触。
第一次submit报错runtime error,应该是数组越界或者指针越界的问题,好吧这个点了我也忘了当时是改的哪里了,好像是 p[count]=nums[i][j]这里,我一开始写的是nums[i*numsColSize+j],但是按道理子函数中以二级指针形式传入的二维数组不是不可以用a[][]的形式使用的嘛?另外根据discuss里解答应该是题目默认不能直接返回sums(好像是根据注释里的意思?不然我实在不太懂后两个参数有什么用),if判断赋值参考了discuss进行了修改。
然后这道题充满疑问的accepted了。
代码:
/**
* 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 *p;
p=(int *)malloc(sizeof(int)*r*c);
int count=0;
int count2=0;
int m,n;
int **a,i,j;
a = (int**)malloc(r*sizeof(int*));
*columnSizes=(int*)malloc(r*sizeof(int));
*returnSize=r;
if (r * c != numsColSize * numsRowSize) {
r = numsRowSize;
c = numsColSize;
}
for(i=0;i<numsRowSize;i++){
for(j=0;j<numsColSize;j++){
p[count]=nums[i][j];
count++;
}
}
for(m=0;m<r;m++){
a[m] = (int*)malloc(c*sizeof(int));
(*columnSizes)[m]=c;
for(n=0;n<c;n++){
a[m][n]=p[count2];
count2++;
}
}
return a;
}
写一半出去玩了,好了,也算是今日事今日毕了。